【发布时间】:2018-07-29 15:10:17
【问题描述】:
我正在尝试从两个不同文件的行中构建一个列表。
文件1.txt
['2.02', '-3.88', '15.25']
['4.40', '-2.36', '14.97']
['5.44', '0.34', '7.34']
['5.76', '0.41', '7.60']
['5.35', '0.19', '13.95']
文件2.txt
['P1']
['P2']
['P3']
['P4']
['P5']
理想的输出
['2.02', '-3.88', '15.25', 'P1']
['4.40', '-2.36', '14.97', 'P2']
['5.44', '0.34', '7.34', 'P3']
['5.76', '0.41', '7.60', 'P4']
['5.35', '0.19', '13.95', 'P5']
我尝试简单的添加线条
combined = open('file1.txt').readlines() + open('line2.txt').readlines()
输出
["['2.02', '-3.88', '15.25']\n", "['4.40', '-2.36', '14.97']\n", "['5.44', '0.34', '7.34']\n", "['5.76', '0.41', '7.60']\n", "['5.35', '0.19', '13.95']\n", 'P1\n', 'P2\n', 'P3\n', 'P4\n', 'P5\n']
我还写了一个函数,试图将两者合并到第三个文件 file3.txt
def combiner():
with open("file1.txt", 'r') as file1:
with open('file2.txt', 'r') as file2:
with open('file3.txt',"w") as file3:
clines = file1.readlines()
plines = file2.readlines()
#Write to third file
for i in range(len(clines)):
line = clines[i].strip() + plines[i]
file3.write(line)
但它仍然写在 2 个不同的列表中
cat file3.txt
['2.02', '-3.88', '15.25']['P1']
['4.40', '-2.36', '14.97']['P2']
['5.44', '0.34', '7.34']['P3']
['5.76', '0.41', '7.60']['P4']
['5.35', '0.19', '13.95']['P5']
最好是返回这样一个列表的函数。
【问题讨论】:
-
如果您还要生成进入文件的数据,则可能值得考虑以某种方式序列化数据。 Pickling 是 Python 中的标准方式。