[python]Writing to temporary file

Supposed you have collected a list item known as ip_collections, and you want to write the list to a temp file.

import tempfile
with tempfile.TemporaryFile() as tf:
    for ip in ip_collections:
        tf.write(bytes(ip + '\n', 'utf-8'))
    tf.seek(0)

Need to convert the string in byte, the tf.seek(0) is to re-wind the pointer back to the start of the file.

After the code exits the with context the temp file is removed.

Supposed you want to store the values of temp file into a variable for some other purpose before removal.

import tempfile
base_list = []
with tempfile.TemporaryFile() as tf:
    for ip in ip_collections:
        tf.write(bytes(ip + '\n', 'utf-8'))
    tf.seek(0)
    base_list = tf.read().decode().split()
    tf.seek(0)

print(base_list)

Need to rewind the start of file with tf.seek(0) so that all items in the temp file will be transferred to base_list. Need to take note that tf.seek(0) has to be put outside for loop otherwise the values will be overwritten on each iteration.
the print statement is for testing if the list is stored.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s