【发布时间】:2015-05-19 06:56:47
【问题描述】:
我有一个脚本 - 在 Windows 中完美运行,但是当我尝试在 Ubuntu 中运行它时,它吐出了错误消息:
IndexError: 列表索引超出范围。
这是一个非常简单的脚本:它导入CSV 文件,读取行,将每行中的第一项打印到列表中,使用set() 删除重复项,然后将这个新列表写入文件。
import csv, glob
for x in glob.glob("*raw_vcf.csv"):
csv_f = open(x, "r")
data = [c for c in csv.reader(csv_f)]
frags_unique = []
def frag_list(vcf_data, uniquefrags):
"""
User input: an imported .vcf file (='vcf_import'); an empty list
(= 'uniquefrags').
'frag_list' takes 'vcf_import', reads each row/list, taking the first item
and attaching only unique values to 'uniquefrags', using the set() function.
First row (header row) in 'vcf_data' is deleted; not needed.
"""
del vcf_data[0]
list_1 = []
for row in vcf_data:
list_1.append(row[0])
for item in list(set(list_1)):
uniquefrags.append(item)
frag_list(data, frags_unique)
out = open("output_unique_frags.txt","w")
for frags in frags_unique:
out.write(frags+"\n")
out.close()
具体是模块中出现的错误:
Traceback (most recent call last):
File "PRIME_unique_frags.py", line 50, in <module>
frag_list(data, frags_unique)
File "PRIME_unique_frags.py", line 46, in frag_list
list_1.append(row[0])
IndexError: list index out of range
但老实说,我看不出它有什么问题,因为它可以在我的 Windows 操作系统上运行;尝试用不同的方式重写它,但没有成功。
一些样本输入数据(“*_raw_vcf.csv”):
A,B,C,D,E
1,2,3,4,5
1,5,4,3,2
2,3,4,5,6
2,3,4,7,8
3,4,5,6,7
理论上应该(并且在 Windows 中)应该生成一个文件(“output_unique_frags.txt”;A 列中的唯一值):
1
2
3
【问题讨论】:
-
使用调试器或打印语句来找出 Linux 上 row 的值是什么。然后你可以确定为什么你会得到 IndexError。不过,我认为@warvariuc 的回答非常接近主题
-
在 frag_unique=[] 之后使用 print 语句,例如 print csv_f 来查看正在读取的 csv 并在 del vcf_data[0] 之后使用 print del vcf_data 查看并说出正在打印的内容
标签: python linux windows csv ubuntu