[英]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.