Python错误:(索引器错误:列表索引超出范围)尝试将行写入CSV
我正在尝试将CSV文件拆分为多个文件。如果我从命令行使用它,代码可以正常工作 我正在cmd中运行Python csv\u splitterFunction.py C:\Users\xlViki\Desktop\Python\Journal.pyPython错误:(索引器错误:列表索引超出范围)尝试将行写入CSV,python,python-3.x,Python,Python 3.x,我正在尝试将CSV文件拆分为多个文件。如果我从命令行使用它,代码可以正常工作 我正在cmd中运行Python csv\u splitterFunction.py C:\Users\xlViki\Desktop\Python\Journal.py import sys number_of_outfiles = 4 if __name__ == "__main__": k = [] for i in range(number_of_outfiles):
import sys
number_of_outfiles = 4
if __name__ == "__main__":
k = []
for i in range(number_of_outfiles):
k.append(open(r'C:\Users\xlViki\Desktop\Python\Output_' + str(i) + '.csv','w'))
with open(sys.argv[1]) as inf:
for i, line in enumerate(inf):
if line[-1] == '\n': line = line[:-1]
if i == 0:
headers = line
[x.write(headers + '\n') for x in k]
else:
k[i % number_of_outfiles].write(line + '\n')
[x.close() for x in k]
但是,当我试图将代码转换为下面这样的函数并在Python shell中运行时(在空闲状态下按F5),我得到了一个超出范围的错误:
这是我收到的输出:
C:\Users\xlViki\Desktop\Python\Output_0
1
<_io.TextIOWrapper name='C:\\Users\\xlViki\\Desktop\\Python\\Output_0.csv' mode='w' encoding='cp1252'>
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
Main(r'C:\Users\xlViki\Desktop\Python\Journal.csv')
File "C:\Users\xlViki\Desktop\Python\csv_splitterFunction.py", line 22, in Main
k[i % number_of_outfiles].write(line + '\n')
IndexError: list index out of range
C:\Users\xlViki\Desktop\Python\Output\u 0
1.
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
Main(r'C:\Users\xlViki\Desktop\Python\Journal.csv')
文件“C:\Users\xlViki\Desktop\Python\csv\u splitterFunction.py”,第22行,在Main中
k[i%输出文件的数量].写入(第+'\n'行)
索引器:列表索引超出范围
你能帮我把这段代码转换成一个函数吗?看起来你需要用inf:打开(文件路径)来取消从
中的所有内容。第一个文件正在打开,但第二行试图在第二个文件打开之前写入该文件。错误消息告诉您,列表索引超出范围异常发生在第22行,k[i%number\u of\u outfiles].write(line+'\n')
。此行将尝试访问k[0]、k[1]、k[2]和k[4],但在循环的第一次迭代中,您只将1个元素放入k中,因此您只能访问k[0]。解决方法是打开所有文件并将它们放入k中,然后进入以开头的循环,并将open(filepath)作为inf:
。
另外,您已经使用了两次i
作为变量,如果您想保持循环嵌套,您应该更改其中一个名称,否则您可以将与open(filepath)作为inf:
取消登录,非常感谢!成功了。现在当我知道答案时,两种代码的区别看起来很明显。谢谢你的解释。非常感谢!就是这样,我取消了代码,它就可以工作了!
C:\Users\xlViki\Desktop\Python\Output_0
1
<_io.TextIOWrapper name='C:\\Users\\xlViki\\Desktop\\Python\\Output_0.csv' mode='w' encoding='cp1252'>
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
Main(r'C:\Users\xlViki\Desktop\Python\Journal.csv')
File "C:\Users\xlViki\Desktop\Python\csv_splitterFunction.py", line 22, in Main
k[i % number_of_outfiles].write(line + '\n')
IndexError: list index out of range