将多个文件的列合并到一个文件 - Python

1 投票
2 回答
4373 浏览
提问于 2025-04-18 02:45

我有几百个文本文件,里面有很多信息。每个文件都有三列(前两列在所有文件中都是一样的)。

我需要把所有文件的第三列合并到一个新文件里,并且在每列的开头加上一个标题,标题是对应文件的名字。

这些文本文件的三列内容是这样的:

-118.33333333333279 40.041666666667908 11.409999847412109
-118.29166666666612 40.041666666667908 11.090000152587891
-118.24999999999946 40.041666666667908 10.920000076293945
-118.20833333333279 40.041666666667908 10.949999809265137

我想要创建的文本文件应该是这样的:

Name_of_file_1 Name_of_file_2 Name_of_file_3
3rd_Column_File_1 3rd_Column_File_2 3rd_Column_File_3
3rd_Column_File_1 3rd_Column_File_2 3rd_Column_File_3
3rd_Column_File_1 3rd_Column_File_2 3rd_Column_File_3
3rd_Column_File_1 3rd_Column_File_2 3rd_Column_File_3

这样做可能吗?我找不到方法来实现。请帮帮我!!!

Pepo

2 个回答

0

我会用一些Unix工具来处理这个问题:

mkfifo pipe1
mkfifo pipe2
mkfifo pipe3

cut -d " " -f 3 text1.csv > pipe1 &
cut -d " " -f 3 text2.csv > pipe2 &
cut -d " " -f 3 text3.csv > pipe3 &

paste pipe1 pipe2 pipe3 > final.csv

rm pipe1 pipe2 pipe3

下面是使用的工具链接:

你可以参考上面的代码示例,来开发你自己的脚本。

0

这是一种实现方法。下面是代码中的注释:

import csv

# List of your files
file_names = ['file1', 'file2']

# Output list of generator objects
o_data = []

# Open files in the succession and 
# store the file_name as the first
# element followed by the elements of
# the third column.
for afile in file_names:
    file_h = open(afile)
    a_list = []
    a_list.append(afile)
    csv_reader = csv.reader(file_h, delimiter=' ')
    for row in csv_reader:
        a_list.append(row[2])
    # Convert the list to a generator object
    o_data.append((n for n in a_list))
    file_h.close()

# Use zip and csv writer to iterate
# through the generator objects and 
# write out to the output file
with open('output', 'w') as op_file:
    csv_writer = csv.writer(op_file, delimiter=' ')
    for row in list(zip(*o_data)):
        csv_writer.writerow(row)
op_file.close()

撰写回答