使用Python读取文件头和分隔符

时间:2017-01-11 09:53:26

标签: python csv delimiter

我正在读取给定文件夹中的所有文件(包含Dir,Sub目录和.csv类型的文件,.txt ..)

我需要以下列格式将以下信息输入到输出文件中:

FileLocation, FileName, Delimiter, Columns 

(由分隔符分隔的单元格中所需的所有列)

我正在使用以下脚本,除了分隔符之外它可以正常工作。我尝试过使用csv.sniffer,但它不起作用。

import sys,os,csv

ofilew = open('D:\OutputFile/Columns_Info.csv', 'w')
ofile = open('D:\OutputFile/Columns_Info.csv', 'a')

root = 'D:\UnZipFiles'
path = os.path.join(root)

columninfo = 'FolderLocation, FileName, Delimiter, Columns' + '\n'
ofilew.write(columninfo)

for r,d,f in os.walk(path):
    for file in f:
        fullfilepath = os.path.join(r,file)
        with open(fullfilepath,'r') as f:
            columninfo = f.readline()
            columninfo = columninfo.replace(",", ";")

            output = file +','+ columninfo
            outputfinal = r + ',' + output

            ofile.write(outputfinal)

1 个答案:

答案 0 :(得分:0)

以下方法适合您,它使用Python的csv.sniffer功能来尝试确定用于读取文件的正确方言。这也包含使用的分隔符。

import os, csv

header_output = ['FolderLocation', 'FileName', 'Delimiter', 'Columns']
path = r'D:\UnZipFiles'

with open(r'D:\OutputFile\Columns_Info.csv', 'wb') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(header_output)

    for root, folders, files in os.walk(path):
        for file in files:
            full_file_path = os.path.join(root, file)

            with open(full_file_path, 'rb') as f_input:
                try:
                    dialect = csv.Sniffer().sniff(f_input.read(1024))
                    f_input.seek(0)
                    csv_input = csv.reader(f_input, dialect)
                    header_input = next(csv_input)
                    csv_output.writerow([root, file, dialect.delimiter] + header_input)
                except csv.Error as e:
                    print "{} - could not determine the delimiter".format(file)

作为csv.sniffer的替代方案,你可以设计自己的,但Python的功能要强得多:

def get_delimiter(file_name):            
    cols_found = []

    for delim in [',', ';', '|', '\t']:
        with open(file_name, 'rb') as f_in:
            cols_found.append([len(next(csv.reader(f_in, delimiter=delim))), delim])

    if cols_found[-1][0] > 1:
        return sorted(cols_found)[-1][1]
    else:
        return None


print get_delimiter('my.csv')

这会通过计算第一行中最多列的分隔符来返回可能的分隔符。如果只找到一列,则返回None以指示未找到匹配的分隔符。它可能会引发异常。