简体   繁体   English

使用Python在文件中每个项目前面附加一个字符串

[英]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? 如何读取文本文件并编写循环以在每个单词前面附加单词“ bar”并生成一个新文件?

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() : 您可以使用readlines()获取文件中的行列表,还可以使用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. 这可能会帮助您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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