嘿,我有这个代码,只连接csv文件中的文件夹的所有csv文件。问题是这行代码if i! = 0:
阻止了除第一个csv之外的每个csv的第一行被读取。关于如何修改它以便它可以读取csv
#!/usr/bin/env python
import pandas as pd
import glob, os
import shutil
#import csv files from folder
path = r'/Users/sonia/Animalsmanage/output'
allFiles = glob.glob(path + "/*.csv")
with open('finaloutput.csv', 'wb') as outfile:
for i, fname in enumerate(allFiles):
with open(fname, 'rb') as infile:
if i != 0:
infile.readline()
outfile.write(bytearray(b'\n')) # add a empty line
shutil.copyfileobj(infile, outfile)
print(fname + " has been imported.")
答案 0 :(得分:0)
如果要包含输入文件中的所有行并将每个输入文件的输出分隔为空白,可以尝试这样做:
with open('finaloutput.csv', 'wb') as outfile:
for i, fname in enumerate(allFiles):
with open(fname, 'rb') as infile:
shutil.copyfileobj(infile, outfile)
outfile.write(bytearray(b'\n'))
print(fname + " has been imported.")
所以,如果我有3个输入文件:
<强> test1.csv:强>
name,id
dan,22
keith,23
<强> test2.csv:强>
name,id
mike,33
phil,44
<强> test3.csv:强>
name,id
john,5
peter,6
我的输出文件将包含:
name,id
dan,22
keith,23
name,id
mike,33
phil,44
name,id
john,5
peter,6
修改强> 如果您不想在最后添加空白行,则可以使用以下代码:
numFiles = len(allFiles)
with open('finaloutput.csv', 'wb') as outfile:
for i, fname in enumerate(allFiles):
with open(fname, 'rb') as infile:
shutil.copyfileobj(infile, outfile)
if i < numFiles - 1:
outfile.write(bytearray(b'\n'))
print(fname + " has been imported.")