[英]prefix and suffix to each line of a txt using python
我需要將一些文本添加到這樣的文檔中:
原始文件:
C:\listagem.txt
i love python
macdonals hamburger
yolo 4ever
我需要添加一個后綴和一個前綴,因此結果將如下所示:
teste.txt
blablablai love pythongugugugugu
blablablamacdonalds hamburgergugugugugu
blablablayolo 4evergugugugugu
我已經嘗試過這種算法,但是沒有用。
prefix = 'blablabla'
suffix = 'gugugugugu'
dest = ''
with open('C:\listagem.txt', 'r') as src:
with open('teste.txt', 'w') as dest:
for line in src:
dest.write('%s%s%s\n' % (prefix, line.rstrip('\n'), suffix))
我在Windows XP上使用python 3.2.3。
您的代碼主要是文件,但文件名是問題所在。 請參閱Stackoverflow上的此答案 。
像這樣更改路徑:
with open('C:\\listagem.txt', 'r') as src:
..或使用原始字符串 :
with open(r'C:\listagem.txt', 'r') as src: # r'raw string' ignores backslashes
..或您也可以只使用正斜杠-如果可行,我建議您使用它(因為反斜杠很麻煩):
with open('C:/listagem.txt', 'r') as src:
還要注意,樣本輸入文件似乎包含尾隨空格。 在您提供的數據中, i love python
之后有兩個空格,因此您的輸出如下所示:
{prefix}i love python {suffix}
這可能是在您的Stackoverflow問題中引入的,而不是原始文件中引入的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.