Reputation: 21
I have a file example.txt in this format:
a,b,c,d
and I want to convert it to:
a
b
c
d
I wrote this but it is not work:
with open('newline.txt', 'w') as f:
f.write (file("example.txt", "r").read().replace(",", "\n"))
Upvotes: 0
Views: 62
Reputation: 26164
You could do it like this as well:
with open('newline.txt', 'w') as f:
f.writelines (w + '\n' for w in open("example.txt").read().split(","))
Upvotes: 1
Reputation: 8159
it should be:
with open('newline.txt', 'w') as f:
f.write (open("example.txt", "r").read().replace(",", "\n"))
It is stated in documentary, that when opening a file, it’s preferable to use open() instead of invoking file() constructor directly
Upvotes: 0