簡體   English   中英

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

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

以下是我要實現的目標:

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

string = 'bar'

my_new_list = [ string + x for x in my_list]

print my_new_list

問題是我所有的單詞都在一個文本文件中。 例:

離岸價

法茲

放克

如何讀取文本文件並編寫循環以在每個單詞前面附加單詞“ bar”並生成一個新文件?

像那樣?

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

您可以使用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()

這可能會幫助您。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM