python - 将多个文本文件中的特定列合并到一个文件中
问题描述
我input.txt
在每个文件夹中有多个文件夹和一个文本文件 ( )。首先我从 中读取文件夹名称f_names.txt
,然后进入每个文件夹并从每个文件夹中读取第三列input.txt
。代码在这里正常工作。问题是代码合并了输出文件 ( combine.txt
) 中一行中的所有第三列。而我想将每第三列写入输出文件 ( combine.txt
) 作为新列。我怎样才能做到这一点?
这是我的代码:
#!/usr/bin/python
import os
import re
path=os.getcwd()
try:
os.remove("combine.txt")
except OSError:
pass
with open('combine.txt', mode='a') as outfile:
with open('f_names.txt', 'r') as read_f:
for line in read_f:
os.chdir(line.strip())
with open('input.txt', 'r') as f:
data=[]
for line in f:
row = line.split()
data.append(float(row[2]))
outfile.write("%.2f\n" % float(row[2]))
os.chdir("..")
获得的输出(对于两个输入文件):
2.12
3.15
4.18
8.45
2.10
0.12
0.18
0.32
0.21
0.13
所需的输出(对于两个输入文件):
2.12 0.12
3.15 0.18
4.18 0.32
8.45 0.21
2.10 0.13
解决方案
您可以做一些事情来使您的程序正确且“更符合 Python 风格”。
with open('f_names.txt') as read_f:
# Collect the third columns in a list
data = []
for line in read_f:
# No need to chdir()
with open('{}/input.txt'.format(line.strip())) as f:
# This is one column
data.append([float(line.split()[2]) for line in f])
# Do not remove the old file, overwrite it
with open('combine.txt', 'w') as outfile:
# "Transpose" the list of columns into a list of rows
# Write each row
for row in zip(*data):
# Use new-style formatting
outfile.write(" ".join("{:.2f}".format(cell) for cell in row) + "\n")
推荐阅读
- ios - 如何从其句柄(macOS / iOS)中获取库的路径?
- pandas - 在两列之间查找最早和最晚的日期
- python-3.x - 如何修复python sqlite数据库不存储数据
- javascript - Uncaught DOMException (in promise) - 在 serviceworker 中劫持特定的 GraphQL 请求
- swift - Auth0 不会使用 swift 退出
- python - 使用两个数据框创建列
- ios - 在滚动视图滚动时更改标签位置
- python - 编辑目录中的 XML 文件
- wordpress - 如何在插件上使用可插拔功能
- statsd - 带有 statsd 后端的 kamon:直方图中值聚合错误