[英]Add a particular string (in that case "\\\hline" to prepare a table in latex) at the end of each line of a text file with python
我想在文本文件的每一行的末尾添加一个特定的字符串(在这种情况下是“\\hline”以准备乳胶表)
a_file = open("sample.txt", "r")
list_of_lines = a_file.readlines()
for line in range(0, len(list_of_lines)):
list_of_lines[line] = list_of_lines[line] + r' \\\line'
a_file = open("sample2.txt", "w")
a_file.writelines(list_of_lines)
a_file.close()
这是sample.txt
:
line1
line2
line3
这是 output:
l1
\\\linel2
\\\linel3
\\\line%
我想要的是:
l1 \\\line
l2 \\\line
l3 \\\line
问题是您没有删除行尾的换行符'\n'
。
第一行实际上如下所示: 'line1\n'
。 当您添加字符串时,结果是'line1\n \\\line'
,它会在'\n'
的位置显示一个换行符。 所以你首先需要去掉换行符,然后再添加你的字符串和换行符。
此外,我建议使用上下文管理器 ( with
) 打开文件,它比手动打开和关闭文件要安全得多,并且被认为是最佳实践。
with open('sample.txt') as file:
list_of_lines = file.readlines()
for i in range(len(list_of_lines)):
list_of_lines[i] = list_of_lines[i].rstrip() + r'\\\line' + '\n'
with open('sample2.txt', 'w') as file:
file.writelines(list_of_lines)
试试list_of_lines[line].rstrip()
。 似乎在您的 output 中附加了行尾字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.