import tempfile with tempfile.NamedTemporaryFile(mode='w', delete=False) as tf: tf.write('Hello, world!\n') tf.write('This is a temporary file.\n') print(f'Temporary file created: {tf.name}')
Temporary file created: /tmp/tmpenbu1de1
import tempfile with tempfile.NamedTemporaryFile(mode='w+', delete=False) as tf: tf.write('Hello, world!\n') tf.write('This is a temporary file.\n') tf.seek(0) lines = tf.readlines() print(f'Read {len(lines)} lines:') for line in lines: print(line.strip())
Read 2 lines: Hello, world! This is a temporary file.In this example, a named temporary file is created in read/write mode with delete=False. The write function is used to write strings to the file. The seek function is used to move the file pointer to the beginning of the file. The readlines function is used to read the lines of the file as a list of strings. The number of lines and the content of each line are printed. The package library for tempfile is a standard library, built-in with Python. We do not need to install any external package to use it.