我有一段代码正在修复我的csv。现在我正在尝试将它作为一个函数放在自己的文件中,我可以用它来处理任何具有相同格式的任意csv文件
但是,我得到以下错误。索引器错误:当我将代码放入函数时,列表索引超出范围
我对函数有更多的了解,我遗漏了一些我看不到的东西
# code that works
with open('File.csv','r') as csv_read:
csv_reader = csv.reader(csv_read)
csv_data = list(csv_reader)
if csv_data[0][0] == '':
csv_data[0][0] = 'Time Stamp'
del csv_data[1]
del csv_data[1]
print('CSV has been fixed')
else:
print('Has already been fixed')
with open('File.csv', 'wb') as writerFile_csv:
writer_csv = csv.writer(writerFile_csv)
writer_csv.writerows(csv_data)
csv_read.close()
writerFile_csv.close()
# code that does not work
def FixCSV(File):
with open(File, 'r') as csv_read:
csv_reader = csv.reader(csv_read)
csv_data = list(csv_reader)
csv_reader = csv.reader(csv_read)
csv_data = list(csv_reader)
if csv_data[0][0] == '':
csv_data[0][0] = 'Time Stamp'
del csv_data[1]
del csv_data[1]
print(File +' has been fixed')
else:
print(File + 'Has already been fixed')
with open(File, 'wb') as writerFile_csv:
writer_csv = csv.writer(writerFile_csv)
writer_csv.writerows(csv_data)
csv_read.close()
writerFile_csv.close()
FixCSV('File.csv')
结果显示代码正常工作:
Time Stamp, /xxxx /130 /T3 /-P* /xxxx,
从
, /xxx /130 /T3 /-P* /xxxx,
Time Stamp, Value,
我有两份
吸取了很好的教训。一定要喝咖啡休息一下。我愚蠢的失手。抱歉浪费了你们的时间
您正在从列表(csv\u读取器)读取到csv\u数据,结果是一个空列表。因此,当您访问csv\u数据[0][0]时,它会给出列表索引超出范围的错误
相关问题 更多 >
编程相关推荐