简体   繁体   中英

Replace text from file for each lines

I want to add new string to all line in a text file.

I have written this program so far:

with open("texte.txt", mode="r") as mf:
    for line in mf:
        data = line + '"'
        print(data) 

But when I print the content, I get an output like this:

line
"
line2
"
line3
"
line"

So I can see it's my first line from my text which is printed OK.

I want my output to be like this:

line1"
line2"
line3"

Thanks for your assistance, I hope you understand me

Each line in a file ends with a line feed. You have to strip that character out of the read input before you're ready to work with the remaining string:

data = line.rstrip() + '"'

Use the splitlines() method:

with open("texte.txt", mode="r") as mf:
    lines = mf.read().splitlines()
    for line in lines:
        data = line + '"'
        print(data) 

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