以下是我想要实现的目标:
my_list = ['foo', 'fob', 'faz', 'funk']
string = 'bar'
my_new_list = [ string + x for x in my_list]
print my_new_list
问题是我的所有单词都在文本文件中。例如:
FOO
FOB
FAZ
芬克
如何读取文本文件并编写循环以在每个单词前面附加单词“bar”并生成新文件?
答案 0 :(得分:2)
喜欢那个?
with open("myfile.txt") as f, open("output.txt", "w") as out:
for line in f:
out.write("bar" + line)
答案 1 :(得分:0)
您可以使用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)
答案 2 :(得分:0)
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()
这可能会对你有帮助。