2014-03-01 73 views
0

我確定這不是太困難,但我沒有看到它。我需要爲文本文件中的所有行添加單引號,並且在引用後直接添加「,text」。將文本文件中的引文添加到每行

所以我不得不

text = xxx (start) 
text = 'xxx',text (finish) 

所以像:

`yourstring = ''.join((''''yourstring',''', 'text')) 

這給正確的輸出,我只是不知道如何在文本做到這一點對所有的行文件?

任何幫助將是偉大的。在讀模式

回答

1

閱讀「文件」,創建新的臨時文件,寫入新的臨時文件中的每一行(concate 'text以及),並刪除舊的「文件」,然後重命名爲「臨時」到「文件」的域名(在每行下面的代碼)閱讀評論:

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'))) 
+1

我的理解是寫入行應該是'o.write(''%s',text \ n「%l [: - 1])' - 即將整個原始行放在引號中。而在我的系統上,os.remove()在os.rename()之前是不需要的 - 是否有這種情況? –

+1

@RoryYorke你的第一個想法很好。我嘗試在Linux'mv'命令中取代'file'的舊內容。我更新我的答案謝謝。 –

1

對上面的回答指針的情侶:

你當然ATT在旅途中所有的新文本與

o.write("'"+l[:-1]+"' yourtext\n") 
+0

以匹配答案do'(「'」+ l [: - 1] +「'yourtext \ n」)'。如果我是正確的,OP也希望'''在行開始之前。 –

+0

感謝您糾正我 –

相關問題