Reputation: 1704
I have the following code:
lines[usernum] = str(user) + "\n"
f = open('users.txt','w')
userstr = str(lines)
f.write(userstr)
Effectively I am modifying the lines
list at usernum
, then writing it back to the original file 'users.txt'
. However, even adding the "\n", everything gets written to one line rather than an individual line for each line in lines
. Why is this?
Upvotes: 0
Views: 4174
Reputation: 250961
Use a for-loop and '\n'
to write each item on a new line:
with open('users.txt','w') as f:
for line in lines:
f.write('{}\n'.format(line))
Calling str()
on a python object like list
or dict
simply returns the str
version of that object, to write it's content to a file you should loop over it.
Demo:
lines = [1, 'foo', 3, 'bar']
with open('users.txt','w') as f:
for line in lines:
f.write('{}\n'.format(line))
...
>>> !cat users.txt
1
foo
3
bar
Upvotes: 1
Reputation: 387687
That is because str(lines)
will not do what you expect it to do:
>>> lst = ['This', 'is a\n', 'fancy\n', 'list']
>>> print(str(lst))
['This', 'is a\n', 'fancy\n', 'list']
As you can see, it will write a representation of the list, and not print out the individual lines. You can use str.join
to combine the list elements:
lines[usernum] = str(user)
with open('users.txt', 'w') as f:
f.write('\n'.join(lines))
Using '\n'
as the join character will make sure that a newline is inserted between each list element, so you do not need to take care of adding it to every item manually.
Furthermore, when working with files, it is recommended to use the with
statement when opening them, to make sure that they are closed correctly when you are done working with them.
Upvotes: 2
Reputation: 1121992
You are writing the string representation of the list to the file.
String representations of Python containers use the representation of the contents, not directly write strings.
Use the writelines()
function to write a sequence of strings:
f.writelines(lines)
or write each line separately:
for line in lines:
f.write(line)
or join the lines into one long string:
f.write(''.join(lines))
The latter also allows you to add the newlines at the time of writing, by using \n
as the joining string:
f.write('\n'.join(lines))
where lines
contains strings without newlines.
Upvotes: 1