简体   繁体   中英

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"))

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(","))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM