[英]Can someone please tell me what am I doing wrong New to Python
My requirement is to look through a folder and combine only the csv files in it into one.我的要求是浏览一个文件夹并将其中的 csv 文件合并为一个。 The csv files are consistent but cannot be just concatenated. csv 文件是一致的,但不能只是串联。 I am only interested in rows where the first element in the row is a date else I need to discard that row.我只对行中第一个元素是日期的行感兴趣,否则我需要丢弃该行。
The code that I have made progress till now is below which as usual is not working:到目前为止,我已经取得进展的代码如下,照常不起作用:
import os
import csv
from dateutil.parser import parse
def datecheck(string):
try:
parse(string)
return True
except ValueError:
False
file_ext = "csv"
os.chdir ("C:\\BANK_PROJECT\\FILES\\RAW_SOURCE_FILES")
file_list = os.listdir("C:\\BANK_PROJECT\\FILES\\RAW_SOURCE_FILES")
with open("outfile.csv", "w") as outfile:
print(file_list)
for file in file_list:
if file.__contains__(".csv"):
with open(file, 'r') as infile:
data = csv.reader(infile)
for row in data:
if len(row) > 0:
if datecheck(row[0]):
outfilewriter = csv.writer(outfile)
outfilewriter.writerows(row)
else:
continue
import csv
from glob import glob
from dateutil.parser import parse
def datecheck(string):
try:
parse(string)
return True
except ValueError:
False
files = glob('*.csv')
with open('outfile.csv', 'w') as outfile:
writer = csv.writer(outfile)
for file in files:
with open(file) as infile:
reader = csv.reader(infile)
data = [row for row in reader if datecheck(row[0])]
writer.writerows(data)
Input file 1:输入文件 1:
new,1,2,3
2012-01-19 17:21:0,1,2 ,3
2012-01-19,1,2,3
xx,2,3,4
Input File 2:输入文件 2:
new,1,2,3
2012-03-19 17:21:0,1,2 ,3
yy,1,2,3
2012-04-19,1,2,3
xx,2,3,4
Output: Output:
2012-01-19 17:21:0,1,2 ,3
2012-01-19,1,2,3
2012-03-19 17:21:0,1,2 ,3
2012-04-19,1,2,3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.