gpt4 book ai didi

python - 使用 CSV Sniffer 确定分隔符,但不适用于多个文件

转载 作者:行者123 更新时间:2023-12-01 02:00:06 28 4
gpt4 key购买 nike

我使用 CSV Reader 中的 Sniffer 类来确定 CSV 文件中的分隔符,它适用于单个文件,但如果我添加循环并将其指向具有相同 CSV 的文件夹,则会抛出错误出现此错误:

File "delimiter.py", line 17, in read_csv_delimit
reader = csv.reader(csvfile, dialect)
TypeError: "delimiter" must be a 1-character string

脚本如下所示:

#!/usr/local/bin/python3

import csv
import os

def read_csv_delimit(file_dir, csv_file):
# Initialise list
file_csv = []
# Open csv & check delimiter
with open(file_dir + "/" + csv_file, newline='', encoding = "ISO-8859-1") as csvfile:
dialect = csv.Sniffer().sniff(csvfile.read(1024))
csvfile.seek(0)
reader = csv.reader(csvfile, dialect)
for item in reader:
file_csv.append(item[0])
#del file_csv[0]
return file_csv

def split_path(full_path):
#path = path.rstrip(os.sep)
head, tail = os.path.split(full_path)
return (head, tail)


machine_dir = input("Drop the folder here: ")

# Get list of machine csv
machines = os.listdir(machine_dir)

for machine in machines:
print(machine)
#file_dir, csv_file = split_path(csv_file)
machine_list = read_csv_delimit(machine_dir, machine)
print(machine_list)

最佳答案

根据跟踪信息,您的脚本似乎确实选择了非 CSV 文件。您可以使用 glob用于微调搜索模式以仅拾取您想要的文件的模块,但即使是简单的扩展名查找也应该足够了:

target = input("Drop the folder here: ")

machine_list = [read_csv_delimit(target, m) for m in os.listdir(target) if m[-4:] == ".csv"]
print(machine_list)

强烈建议检查输入的目录有效性,即使它是使用最简单的 os.path.isdir(target) 执行的。

我还建议您使用os.pathread_csv_delimit() 函数中构建路径的工具,例如:

with open(os.path.join(file_dir, csv_file), newline='', encoding = "ISO-8859-1") as csvfile:

关于python - 使用 CSV Sniffer 确定分隔符,但不适用于多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49770838/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com