【发布时间】:2021-01-21 12:45:24
【问题描述】:
我有两个文件夹,每个文件夹包含五个文本文件(input1.txt、input2.txt、input3.txt、input4.txt、input5.txt)。我正在尝试从每个文本文件中读取第四列并将其写入输出文件 (output.txt)。我想在输出文件中有两列(第一列和第二列分别是文件夹 1 和文件夹 2 中的文本文件中的 5 个数字),但我的脚本只将一列写入输出文件。你知道如何修复我的代码以在输出文件中获取两列吗?
获得的输出:
0.12
0.17
0.54
0.79
1.15
2.24
3.51
4.01
5.08
6.22
期望的输出:
0.12 2.24
0.17 3.51
0.54 4.01
0.79 5.08
1.15 6.22
脚本:
# !/usr/bin/env python3
import os
import re
with open("output.txt", mode='w') as out:
folders = ["folder1", "folder2"]
for folder in folders:
os.chdir(folder)
search_word = 'The result is:'
for i in range(1, 6):
with open('input'+ str(int(i)) + '.txt', mode='r') as infile:
for lines in infile:
if search_word in lines:
columns = lines.split()
out.write( "%.2f\n" % (float(columns[4])))
os.chdir("..")
【问题讨论】:
标签: python-3.x