我的程序运行良好;然后,它会给我一个错误,指出以下内容:
Traceback (most recent call last):
File "K:\56_CRT\1 PST EEIC\2_Projects\InternetOfTests\Project_Jacob\Full
Program (Testing).py", line 228, in <module>
inputSamplesm[idx] = [data[0], data[1]]
IndexError: list index out of range
我不知道那是什么。我一直在尝试操纵数组和索引,但是似乎无法解决问题。请指教。在下面找到我的代码:
with open('MagnaDC Set Points.csv', 'r') as csvfile1, open('Amatek Set Points.csv', 'r') as csvfile2:
dataset = csv.reader(csvfile1, csvfile2, delimiter=',')
next(dataset)
rows = list(dataset)
inputSamplesm = np.empty([len(rows), 2], dtype=float)
outputSamplesm = np.empty([1,3], dtype=float)
inputSamplesa = np.empty([len(rows), 2], dtype=float)
outputSamplesa = np.empty([1,3], dtype=float)
testStartTime = time.time()
for idx, data in enumerate(rows):
inputSamplesm[idx] = [data[0], data[1]]
inputSamplesa[idx] = [data[0], data[1]]
s.sendall('VOLT {0}\n'.format(data[0]).encode('utf-8'))
conn.write('VOLT {0}\n'.format(data[0]).encode('utf-8'))
stopTime = testStartTime + int(data[1])
while time.time() < stopTime:
s.sendall('MEAS:VOLT?\n'.encode('utf-8'))
voltm = s.recv(1024)
voltm = float(voltm)
答案 0 :(得分:3)
根据documentation csv
模块的reader
函数,仅接受一个文件描述符以读取内容。当您为函数传递两个文件描述符时,尽管解释器不会引发任何异常,但它会默默地忽略第二个文件并仅解析第一个文件。您可能需要通过一个一个地解析来重新访问代码,并确保两个文件都不为空。
演示
file1.csv
name,age
swadhikar,29
file2.csv
name,age
elavarasan,29
示例脚本
import csv
with open('file2.csv') as f1, open('file1.csv') as f2:
reader_obj = csv.reader(f1, f2, delimiter=',')
next(reader_obj)
for line in reader_obj:
print(line)
结果
/usr/bin/python3.6 /home/swadhi/PycharmProjects/pyselenium/python/stackoverflow/so_51741056.py
['elavarasan', '29']
您可以使用两个分别使用csv.reader()
和zip
创建的阅读器引用来解析这两个csv文件,以对其进行迭代,如下所示。
import csv
with open('file1.csv') as f1, open('file2.csv') as f2:
f1_reader_obj = csv.reader(f1)
f2_reader_obj = csv.reader(f2)
next(f1_reader_obj)
next(f2_reader_obj)
for file1_line, file2_line in zip(f1_reader_obj, f2_reader_obj):
line1_as_str = ' '.join(file1_line)
line2_as_str = ' '.join(file2_line)
print(line1_as_str)
print(line2_as_str)
结果
/usr/bin/python3.6 /home/swadhi/PycharmProjects/pyselenium/python/stackoverflow/so_51741056.py
swadhikar 29
elavarasan 29