Python 2.7:Write to File Instantly

Python 2.7 : Write to file instantly

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)

How to create a text file with python 2.7

Call this in the same directory as your script in command prompt.

python your_script.py > output.txt

If you want to do this within the script itself:

with open("output.txt", "w") as f: 
f.write("Random Number")

Writing to file during infinite while

To sum up all the answers in one:

try:
with open('log.txt', 'a') as fichier:
while True:
for hostname in hostnames:
ping = os.system(" Ping " + str(hostname))
if ping == 1:
print("DOWN")
fichier.flush()
fichier.write(str(date) + " " + str(hostname) + '\n' + '\n')
else:
print("UP")
except KeyboardInterrupt:
print("Done!")

Correct way to write line to file?

This should be as simple as:

with open('somefile.txt', 'a') as the_file:
the_file.write('Hello\n')

From The Documentation:

Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.

Some useful reading:

  • The with statement
  • open()
    • 'a' is for append, or use
    • 'w' to write with truncation
  • os (particularly os.linesep)

how to print directly to a text file in both python 2.x and 3.x?

You can use the print_function future import to get the print() behaviour from python3 in python2:

from __future__ import print_function
with open('filename', 'w') as f:
print('some text', file=f)

If you do not want that function to append a linebreak at the end, add the end='' keyword argument to the print() call.

However, consider using f.write('some text') as this is much clearer and does not require a __future__ import.

Python 2.7: Print to File

If you want to use the print function in Python 2, you have to import from __future__:

from __future__ import print_function

But you can have the same effect without using the function, too:

print >>f1, 'This is a test'

How to make python write on a file live

You should be able to write using the flush() function.

outputFile.flush()

More informations on the flush() function on this link: https://docs.python.org/2/library/functions.html#print

That's nearly the same request than this one: Python 2.7 : Write to file instantly



Related Topics



Leave a reply



Submit