[英]prefix and suffix to each line of a txt using python
I need to add some texts to a document like this: 我需要将一些文本添加到这样的文档中:
Original document: 原始文件:
C:\listagem.txt
i love python
macdonals hamburger
yolo 4ever
I need to add a suffix and a prefix, so the result would look like this: 我需要添加一个后缀和一个前缀,因此结果将如下所示:
teste.txt
blablablai love pythongugugugugu
blablablamacdonalds hamburgergugugugugu
blablablayolo 4evergugugugugu
I already tried this algorithm, but it didn't work. 我已经尝试过这种算法,但是没有用。
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))
I am using python 3.2.3 on windows XP. 我在Windows XP上使用python 3.2.3。
Your code is mostly file, but the filename is the problem. 您的代码主要是文件,但文件名是问题所在。 See this answer on Stackoverflow . 请参阅Stackoverflow上的此答案 。
Change your path like so: 像这样更改路径:
with open('C:\\listagem.txt', 'r') as src:
..or using raw strings : ..或使用原始字符串 :
with open(r'C:\listagem.txt', 'r') as src: # r'raw string' ignores backslashes
..or you can maybe just use forward slashes - if this works, I'd recommend it (as backslashes are a pain): ..或您也可以只使用正斜杠-如果可行,我建议您使用它(因为反斜杠很麻烦):
with open('C:/listagem.txt', 'r') as src:
Also note that your sample input file appears to contain trailing whitespace. 还要注意,样本输入文件似乎包含尾随空格。 In your supplied data, there is two spaces after the i love python
, thus your output looks like so: 在您提供的数据中, i love python
之后有两个空格,因此您的输出如下所示:
{prefix}i love python {suffix}
This might have been introduced in your Stackoverflow question, rather than the original file. 这可能是在您的Stackoverflow问题中引入的,而不是原始文件中引入的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.