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)
Answer from glibdud on Stack OverflowWriting to file using Python - Stack Overflow
How does one read and write to files in python?
Two ways of saving output to a file. Which one is better ? and why?
python - Correct way to write line to file? - Stack Overflow
Videos
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:
I have watched many a YouTube video, but alas, it just confused me more. What is the python equivalent to things like File.WriteLine in c#?
Thanks in advance.
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