[英]python no idea what's wrong
我想编写一个函数来实现打开文件->选择某个列->取出不重复的名称->将名称写入另一个文件。 我写了一些这样的代码:
def method2(filename):
name = filename + '.txt'
content = open(name,'r')
for line in content:
values = line.split()
a = values[1]
print(a)
错误是:
>>> method2('test')
d8:c7:c8:5e:7c:2d,
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
method2('test')
File "C:/Users/Yifan/Desktop/data/Training data/Method2.py", line 10, in method2
a = values[1]
IndexError: list index out of range
我的文件如下所示:
1405684432, d8:c7:c8:5e:7d:e8, SUTD_Guest, 57
1405684432, d8:c7:c8:5e:7c:89, SUTD_ILP2, 74
1405684432, d8:c7:c8:5e:7c:8d, SUTD_GLAB, 74
1405684432, b0:c5:54:dc:dc:6c, ai-ap1, 85
当您到达第二行时,该行看起来为空,并将其拆分,您只会在values
获得一个空列表。 尝试访问元素1
(即第二个元素)失败,因为没有第二个元素。
尝试将if len(values) > 0:
放入其中以保护a = line[1]
。
干得好
test.py
def read_file(filename):
file = open(filename)
contents = map(str.strip,file.readlines())
file.close()
return contents
def get_column_values(col_num,lines):
column_values = []
for line in lines:
if not line:
continue
values = line.split()
#col_num - 1 = index of list
#[:-1] will chop the last char i.e. comma from the string
column_values.append(values[col_num-1][:-1])
return column_values
def remove_duplicates(xList):
return list(set(xList))
def write_file(filename,lines):
file = open(filename,"w")
for line in lines:
file.write("%s\n" % line)
file.close()
def main():
lines = read_file("input.txt")
#Work on 1st Column i.e. 0th index
column_values = get_column_values(1,lines)
entries = remove_duplicates(column_values)
write_file("output.txt",entries)
main()
input.txt中
1405684432, d8:c7:c8:5e:7d:e8, SUTD_Guest, 57
1405684432, d8:c7:c8:5e:7c:89, SUTD_ILP2, 74
1405684432, d8:c7:c8:5e:7c:8d, SUTD_GLAB, 74
1405684432, b0:c5:54:dc:dc:6c, ai-ap1, 85
output.txt 1405684432
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.