我正在尝试使用它来操作大型 txt 文件中的数据。
我有一个包含 2000 多列的 txt 文件,其中大约三分之一的标题包含“Net”一词。我只想提取这些列并将它们写入新的 txt 文件。关于我如何做到这一点有什么建议吗?
我四处搜寻了一下,但没能找到对我有帮助的东西。如果之前曾提出并解决过类似问题,我们深表歉意。
编辑1:谢谢大家!在撰写本文时,3 位用户提出了解决方案,而且它们都运行得很好。老实说,我不认为人们会回答,所以我一两天没有检查,对此感到高兴和惊讶。我印象非常深刻。
编辑2:我添加了一张图片,显示原始txt文件的一部分是什么样子,以防将来对任何人有帮助:
![Sample from original txt-file](https://i.stack.imgur.com/C3K9h.jpg)
一种无需安装第三方模块(如 numpy/pandas)的方法如下。给定一个名为“input.csv”的输入文件,如下所示:
a、b、c_net、d、e_net
0,0,1,0,1
0,0,1,0,1
(删除中间的空行,它们只是为了格式化
这篇文章的内容)
下面的代码可以实现你想要的功能。
import csv
input_filename = 'input.csv'
output_filename = 'output.csv'
# Instantiate a CSV reader, check if you have the appropriate delimiter
reader = csv.reader(open(input_filename), delimiter=',')
# Get the first row (assuming this row contains the header)
input_header = reader.next()
# Filter out the columns that you want to keep by storing the column
# index
columns_to_keep = []
for i, name in enumerate(input_header):
if 'net' in name:
columns_to_keep.append(i)
# Create a CSV writer to store the columns you want to keep
writer = csv.writer(open(output_filename, 'w'), delimiter=',')
# Construct the header of the output file
output_header = []
for column_index in columns_to_keep:
output_header.append(input_header[column_index])
# Write the header to the output file
writer.writerow(output_header)
# Iterate of the remainder of the input file, construct a row
# with columns you want to keep and write this row to the output file
for row in reader:
new_row = []
for column_index in columns_to_keep:
new_row.append(row[column_index])
writer.writerow(new_row)
请注意,没有错误处理。至少有两个需要处理。第一个是检查输入文件是否存在(提示:检查 os 和 os.path 模块提供的功能)。第二个是处理空白行或列数不一致的行。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)