简体   繁体   中英

Append text in every line of txt in Python

I've a text file with many lines. I need to append to every line a text in Python.

Here an example:

Text before:

car
house
blog

Text modified:

car: [word]
house: [word]
blog: [word]

If you just want to append word on each line this works fine

file_name = 'YOUR_FILE_NAME.txt' #Put here your file

with open(file_name,'r') as fnr:
    text = fnr.readlines()

text = "".join([line.strip() + ': [word]\n' for line in text])

with open(file_name,'w') as fnw:
    fnw.write(text)

But there are many ways to do it

Read the text in a list:

f = open("filename.dat")
lines = f.readlines()
f.close()

append text:

new_lines = [x.strip() + "text_to_append" for x in lines]  
# removes newlines from the elements of the list, appends 
# the text for each element of the list in a list comprehension

Edit: for completness, a more pythonic solution with writing the text to a new file:

with open('filename.dat') as f:
    lines = f.readlines()
new_lines = [''.join([x.strip(), text_to_append, '\n']) for x in lines]
with open('filename_new.dat', 'w') as f:
    f.writelines(new_lines)

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