简体   繁体   中英

Appending a string in front of every item in the file using Python

The following is what I am trying to achieve:

my_list = ['foo', 'fob', 'faz', 'funk']

string = 'bar'

my_new_list = [ string + x for x in my_list]

print my_new_list

The problem is all my words are in a text file. Example:

foo

fob

faz

funk

How to read the text file and write a loop to append the word 'bar' in front of each word and generate a new file?

Like that?

with open("myfile.txt") as f, open("output.txt", "w") as out:
    for line in f:
        out.write("bar" + line)

You can get a list of lines in a file using readlines() and you can write lines to a file using writelines() :

with open('/path/to/infile') as infile:
    lines = infile.readlines()

string = 'bar'
my_new_list = [string + x for x in lines]

with open('/path/to/outfile', 'w') as outfile:
    outfile.writelines(my_new_list)
file_object = open('example.txt','r')
output = open('data','w+')
string = 'bar'
for line in file_object:
    output.write(string+line)
file_object.close()
output.close()

this is may help you.

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