按列追加 5 个文本文件

Appending 5 text files columnwise

我想添加 4 个文本文件的所有行,并有一个包含 5 列的输出文件。我的一个文件有两列。我尝试用 csv.reader 来做,但我无法得到正确的结果。目前我正在处理这段代码:

from os import walk
import csv
mypath = 'C:\Users\files to append'     
o_data = []
files = []
for (dirpath, dirnames, filenames) in walk(mypath):
    files.extend(filenames)
    break
print(files)
for afile in files:
    file_h=open(afile)
    a_list = []
    a_list.append(file_h.read())
    csv_reader = csv.reader(file_h, delimiter = ' ')
    for row in csv_reader:
        a_list.append(row[0])
    o_data.append((n for n in a_list))
    file_h.close()

with open('output.dat', 'w') as op_file:
    csv_writer = csv.writer(op_file, delimiter = ' ')
    for row in list(zip(*o_data)):
        csv_writer.writerow(row)

我的五个文本文件看起来像这样,具有不同的值:

SCALAR
ND   9418
ST  0
TS     45000.34
0.0000
100.02

结果应该是这样的(4 headers 和 5 列数):

SCALAR SCALAR SCALAR SCALAR  
ND   9418 ND   9418 ND   9418 ND   9418 
ST  0 ST  0 ST  0 ST  0 ST  0 
TS 45000.34 TS 45000.34 TS 45000.34 TS 45000.34 
0.0000 1.0000 2.4344 4.5656 81.2123
100.02 123.32 333.85 435.33 987.11

如有任何建议,我将不胜感激。

尝试 2

我尝试用其他方式重写它。所以这是我的解决方案,但它不能正常工作。我不明白为什么它不能将 "output1.out" 重命名为 "output.out"

这是代码:

进口os

""" 请将所有必要的数据放入目录 """

f = []
for file in os.listdir('C:\Users\Append'):
    if file.endswith(".dat"):
        f.append(file)
        print(file)
        os.rename(file,"input.dat")
        file = file.rsplit('.', 1)[0]
        print(file)
        with open("output.out", "r") as textfile1, open("input.dat", "r") as textfile2,\
             open("output1.out", "w") as out:
            for x, y in zip(textfile1, textfile2):
                x = x.strip()
                y = y.strip()
                print("{0} {1}".format(x, y), file = out)
                print(fname)
         os.rename("input.dat", file+".txt")
    os.rename("output1.out", "output.out" )
print(f) # just for checking

以下应该符合您的要求。它不是使用 os.walk(),而是使用 glob.glob() 来获取合适的文件列表,例如*.dat 用于所有 dat 文件,或者您可以根据您的文件名使用 i*.dat

它将每个文件读入一个data列表,然后使用zip(*data)技巧将列的行读取为行的列。有了这些,它然后使用 chain.from_iterable() 将每一行的每个列表组合成一个列表,并将其写到输出 CSV 文件中,并以空格作为分隔符。

from itertools import chain
import glob
import csv

with open('output.csv', 'w', newline='') as f_output:
    csv_output = csv.writer(f_output, delimiter=' ')
    data = []

    for filename in glob.glob('c*.txt'):
        with open(filename, newline='') as f_input:
            csv_input = csv.reader(f_input, delimiter=' ', skipinitialspace=True)
            data.append(list(csv_input))

    for row in zip(*data):
        csv_output.writerow(chain.from_iterable(row))

给你这样的东西:

SCALAR SCALAR SCALAR SCALAR SCALAR
ND 9418 ND 9419 ND 9420 ND 9421 ND 9422
ST 0 ST 1 ST 2 ST 3 ST 4
TS 45000.34 TS 45000.35 TS 45000.36 TS 45000.37 TS 45000.38
0.0000 0.0001 0.0002 0.0003 0.0004
100.02 100.03 100.04 100.05 100.06