我想添加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个标题和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”
这是代码:
导入它们
“”“请把所有必要的数据放入目录”“”
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句