csv 尝试从python中的.split()函数读取数组后,出现列表索引超出范围错误-返回只有1个值的数组

guykilcj  于 2023-05-04  发布在  Python
关注(0)|答案(1)|浏览(160)

我有无法从其他程序编辑的csv文件。我想按符号分割文件”;”使用split函数。
1:我打开csv文件2:我使用readlines()3:我使用split(;)4.读取拆分后的值da_split[2]时出错(返回一维数组)
验证码:

`    def get_data_csv(self):

        data = []
        
        f = open("./filename.csv", 'r')
        data = f.readlines()

        print('Printout before splitting:')
        print(data)
        data1 = data

        for da in data1:
            da_split = []
            da_split = da.split(";")
            print("Splitted: ")
            print(da_split)

            self.list_date.append(da_split[0])
            self.list_tempAS.append(self.changeStrtoFloat(da_split[1]))`

输出:

Program Start
Printout before splitting:
['Vorbereitung\n', 'Datum;Uhrzeit;Phase;Screen;Key;Interruptions;Temperatur AS;Temperatur SS;Gewichtswerte AS;Gewichtswerte SS;Info/Comment;\n', 'Nov 18;12:59:06;;;;;;;5613.74g;;;\n', 'Nov 18;12:59:01;;;;;;;5630.78g;;;\n', 'Nov 18;12:59:00;;;;;;;;5657.81g;;\n', 'Nov [...]

Splitted: 
['Vorbereitung\n']
Traceback (most recent call last):
  File "C:\Users\sp7820\PycharmProjects\graphLogger\main.py", line 99, in <module>
    main()
  File "C:\Users\sp7820\PycharmProjects\graphLogger\main.py", line 96, in main
    x.get_data_csv()
  File "C:\Users\sp7820\PycharmProjects\graphLogger\main.py", line 44, in get_data_csv
    self.list_tempAS.append(self.changeStrtoFloat(da_split[1]))
IndexError: list index out of range

Process finished with exit code 1

我尝试了str()方法,但它没有任何工作

w8biq8rn

w8biq8rn1#

Printout before splitting:
  ['Vorbereitung\n',
   'Datum;Uhrzeit;Phase;Screen;Key;Interruptions;Temperatur AS;Temperatur SS;Gewichtswerte AS;Gewichtswerte SS;Info/Comment;\n',
   'Nov 18;12:59:06;;;;;;;5613.74g;;;\n',
   'Nov 18;12:59:01;;;;;;;5630.78g;;;\n',
   'Nov 18;12:59:00;;;;;;;;5657.81g;;\n',
   'Nov [...]

第一行中没有;,因此拆分它只产生一个条目。
您可能需要添加一个len(da_split)检查,以自动忽略这些行:

for da in data1:
        da_split = []
        da_split = da.split(";")
        print("Splitted: ")
        print(da_split)

        if len(da_split) >= 2:
            self.list_date.append(da_split[0])
            self.list_tempAS.append(self.changeStrtoFloat(da_split[1]))

另一种选择是使用内置的csv库,避免手动拆分:

import csv
    f = open("./filename.csv", 'r')
    data = list(csv.reader(f, delimiter=';'))

提供以下数据:

[
     ['Vorbereitung'],
     ['Datum', 'Uhrzeit', 'Phase', 'Screen', 'Key', 'Interruptions', 'Temperatur AS', 'Temperatur SS', 'Gewichtswerte AS', 'Gewichtswerte SS', 'Info/Comment', ''],
     ['Nov 18', '12:59:06', '', '', '', '', '', '', '5613.74g', '', '', '']
     ...
   ]

相关问题