Writing to a file immediately

Report a typo

Let's suppose you need to write a very long list to a file and want to see how the writing is performed — for example, to monitor the size of the file and start writing to another one if the size exceeds some threshold. How would you do that?

Look at the code we have written:

long_list = list(range(1000000))
file_name = "my_file.txt"
opened_file = open(file_name, 'w')
for item in long_list:
    # the next line should write each item to my_file.txt
    print(...)
opened_file.close()

In the text field below, write the print() command with correct arguments. For example, you might write print(item) but, obviously, you should specify some other arguments as well. Don't forget about PEP8!

Tip: Remember that if you just use the argument file, the print() function will flush the file only when the buffer is full. You should also use another argument.

Enter a short text
___

Create a free account to access the full topic