Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.7 : Write to file instantly

I realized that when I write into a file using python it wait until the end of my Python file to execute it:

outputFile = open("./outputFile.txt","a") outputFile.write("First") print "Now you have 10sec to see that outputFile.txt is still the same as before" time.sleep(10) outputFile.write("Second") print "Now if you look at outputFile.txt you will see 'First' and 'Second'" 

How am I suppose to make python write instantly to the output file?

like image 872
elbajo Avatar asked Sep 24 '13 14:09

elbajo


People also ask

How do I force Python to write to a file?

fsync() method in Python is used to force write of the file associated with the given file descriptor. In case, we are working with a file object( say f) rather than a file descriptor, then we need to use f. flush() and then os. fsync(f.

How do you continuously write to a file in Python?

The process is pretty straightforward. First, we open the file using the open() method for writing, write a single line of text to the file using the write() method, and then close the file using the close() method.

How do you keep old content when writing to a file in Python?

We can keep old content while using write in python by opening the file in append mode. To open a file in append mode, we can use either 'a' or 'a+' as the access mode. The definition of these access modes are as follows: Append Only ('a'): Open the file for writing.

How do you write to a file line by line in Python?

To write line by line to a csv file in Python, use either file. write() function or csv. writer() function. The csv.


Video Answer


1 Answers

You can use flush() or you can set the file object to be unbuffered.

Details on using that parameter for open() here.

So you would change your open call to -

outputFile = open("./outputFile.txt", "a", 0) 
like image 78
RyPeck Avatar answered Sep 23 '22 06:09

RyPeck