![](/img/trans.png)
[英]Creating, then appending data on to the end of each line on a text file in python
[英]Appending Quotations in Text File to Each line
我確信這不是太難,但我沒有看到它。 我需要在文本文件的所有行中添加單引號,並在引號后直接添加“,text”。
所以我會的
text = xxx (start)
text = 'xxx',text (finish)
像這樣的東西:
`yourstring = ''.join((''''yourstring',''', 'text'))
這給出了正確的輸出,我只是不確定如何為文本文件中的所有行執行此操作?
任何幫助都會很棒。
在讀取模式下讀取“文件”,創建新的臨時文件,在新的臨時文件中寫入每一行(連接'
和其他text
)並刪除舊的'文件',然后將'temp'重命名為'file'名稱(在下面閱讀評論)每行的代碼):
with open("file") as i: # open file for reading, i = input file
with open("temp", "w") as o: # open temp file in write mode, o = output
for l in i: # read line by line
o.write("'%s',text\n" % l[:-1]) # concate ' and text
# ^ ^ added `'` for each line
os.remove("file") # delete old file. Note:this is not needed in postfix system
os.rename("temp", "file") # rename file
編輯:如果要在緩沖區中完全讀取文件並使用join( )
添加'sometext'
字符串。 然后你可以做如下(這我認為不必要的復雜):
with open('file') as f:
file_date = f.read()
updated_file_data = "sometext\n".join(map("'{0}'".format, file_date.split('\n')))
幾個關於上述答案的指針:
你當然可以把所有的新文本都放在一起
o.write("'"+l[:-1]+"' yourtext\n")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.