有人可以告诉我我在做什么错吗Python新手

时间:2020-07-03 05:02:49

标签: python

我的要求是浏览一个文件夹,并将其中的csv文件仅合并到一个文件夹中。 csv文件是一致的,但不能被串联。我只对其中第一个元素是日期的行感兴趣,否则我需要丢弃该行。

我到目前为止所取得的代码低于通常的水平:

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

1 个答案:

答案 0 :(得分:0)

x

输入文件1:

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)

输入文件2:

new,1,2,3
2012-01-19 17:21:0,1,2 ,3
2012-01-19,1,2,3
xx,2,3,4

输出:

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