Printing help f.write()
When writing to files, should I use write() or print()?
python - f.write vs print >> f - Stack Overflow
Attempting to Write to a text file using f.write in Python - Stack Overflow
Videos
file_object = open(“testfile.txt”,”w”)
If I want to write on this file, I see people using the format:
file_object.write(“Hello World”)
And other people use the format
print("Hellow World", file=file_object)Which is more conventional? And is there any difference?
Thanks
print does things file.write doesn't, allowing you to skip string formatting for some basic things.
It inserts spaces between arguments and appends the line terminator.
print "a", "b" # prints something like "a b\n"
It calls the __str__ or __repr__ special methods of an object to convert it to a string.
print 1 # prints something like "1\n"
You would have to manually do these things if you used file.write instead of print.
I disagree somewhat with several of the opinions expressed here, that print >> f is redundant and should be avoided in favour of f.write.
print and file.write are quite different operations. file.write just directly writes a string to a file. print is more like "render values to stdout as text". Naturally, the result of rendering a string as text is just the string, so print >> f, my_string and f.write(my_string) are nearly interchangeable (except for the addition of a newline). But your choice between file.write and print should normally be based on what you're doing; are you writing a string to a file, or are you rendering values to a file?
Sure, print is not strictly necessary, in that you can implement it with file.write. But then file.write is not strictly necessary, because you can implement it with the operations in os for dealing with file descriptors. Really they're operations on different levels, and you should use whichever is more most appropriate for your use (normally the level other nearby code is working on, or the highest level that doesn't get in your way).
I do feel that the print >> f syntax is fairly horrible, and is a really good example of why print should have been a function all along. This is much improved in Python 3. But even if you're writing Python 2 code that you're planning to port to Python 3, it is much easier to convert print >> f, thing1, thing2, thing3, ... to print(thing1, thing2, thing3, file=f) than it is to convert the circumlocution where you roll your own code to do the equivalent of print's rendering and then call f.write(text). I'm pretty sure the semi-automatic converter from Python 2 to Python 3 will even do the conversion for you, which it couldn't possibly do if you avoid the print >> f form.
Bottom line: use print to render values to stdout (or to a file). Use f.write to write text to a file.
f.write can take a string as an argument. So just pass a proper string.
f.write(str(stud.name) + " " + str(stud.grade) + "\n")
You can create the text string first and then write it
text = '{} {}\n'.format(str(stud.name), str(stud.grade))
f.write(text)
For e.g.
text = '{} {}\n'.format(str('John'), str('A'))
#John A
f.write(text)
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.linesepas a line terminator when writing files opened in text mode (the default); use a single'\n'instead, on all platforms.
Some useful reading:
- The
withstatement open()'a'is for append, or use'w'to write with truncation
os(particularlyos.linesep)
You should use the print() function which is available since Python 2.6+
from __future__ import print_function # Only needed for Python 2
print("hi there", file=f)
For Python 3 you don't need the import, since the print() function is the default.
The alternative in Python 3 would be to use:
with open('myfile', 'w') as f:
f.write('hi there\n') # python will convert \n to os.linesep
Quoting from Python documentation regarding newlines:
When writing output to the stream, if newline is
None, any'\n'characters written are translated to the system default line separator,os.linesep. If newline is''or'\n', no translation takes place. If newline is any of the other legal values, any'\n'characters written are translated to the given string.
See also: Reading and Writing Files - The Python Tutorial
Every time you enter and exit the with open... block, you're reopening the file. As the other answers mention, you're overwriting the file each time. In addition to switching to an append, it's probably a good idea to swap your with and for loops so you're only opening the file once for each set of writes:
with open("output.txt", "a") as f:
for key in atts:
f.write(key)
You need to change the second flag when opening the file:
wfor only writing (an existing file with the same name will be erased)aopens the file for appending
Your code then should be:
with open("output.txt", "a") as f: