【发布时间】:2023-01-31 02:53:43
【问题描述】:
我正在尝试用 Python 解析一个 csv 文件,但这些字段是使用制表符而不是空格排列的。所以我想使用 skipinitialspace=True 选项,但它不会跳过制表符(如文档所述)。所以我想出了下面的解决方案,但我想知道是否有更好的解决方案。更好的是更快,使用更少的内存或更优雅。
另外我发布这个问题是因为我正在寻找一种方法来解决这个问题但我找不到,所以这也可能对其他人有帮助。
这是我想出的:
try:
buffer = io.StringIO()
with open('myFile.csv', 'r') as csv_file:
for csv_line in csv_file:
if csv_line == '\n' or csv_line == '\r\n': #skip empty line
continue
if csv_line[:1] == '#': #skip lines that start with # as they are commented out
continue
buffer.write(csv_line.replace('\t', ' ')) #replace all tabs with spaces (otherwise skipinitialspace doesn't work)
buffer.seek(0) #go back to the beginning of the buffer
try:
reader = csv.reader(buffer, delimiter=';', quotechar='"', skipinitialspace=True)
for row in reader:
row = [s.strip() for s in row] #strip leading and trailing whitespace (tabs, spaces, ...)
if (len(row) == 0) or (len(row[0]) == 0): #skip empty line
continue
#ignore everything that starts with a #
if row[0][:1] == '#': #skip lines that start with # as they are commented out
continue
#--- DO STUFF HERE TO PROCESS DATA ---
except csv.Error as e:
return (f'''CSV error: {e}''')
except UnicodeDecodeError as e:
return (f'''Error found in CSV file. Make sure it is in UTF-8 format: {e}''')
except OSError as e:
return ('''Error opening menu file: {e}''')
【问题讨论】: