594380923
594380923

Reputation: 21

new line from a text file

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

Answers (2)

piokuc
piokuc

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

4d4c
4d4c

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

Related Questions