任何人都可以帮我,我是Python的新手,我在分配变量并跳过一些行
时遇到了一些问题我的代码看起来像这样:
import csv
with open('sample.csv', "r") as csvfile:
# Set up CSV reader and process the header
reader = csv.reader(csvfile, delimiter=' ')
skip_lines = csvfile.readlines()[4:] #skip the first four lines
capacity = []
voltage = []
temperature = []
impedance = []
# Loop through the lines in the file and get each coordinate
for row in reader:
capacity.append(row[0])
voltage.append(row[1])
temperature.append(row[2])
impedance.append(row[3])
print(capacity, voltage, temperature, impedance)
您的问题在这里:
skip_lines = csvfile.readlines()[4:]
这将整个文件读取到内存中,并将所有内容都放在skip_lines
中的前4行。到您到达:
for row in reader:
文件处理程序已经用尽。
要跳过文件处理程序中的一行,请使用:
next(csvfile)
由于您想跳过前四个:
for _ in range(4):
next(csvfile)