所以我正在尝试创建一个打开文本文件的函数,逐行读取,然后从中提取数据以创建列表。
def file_open():
filename = str(input("enter file name for perk.py to sort through"))
fob = open(str(filename), 'r')
theList = []
for line in fob:
if not line:
break
x = fob.readline()
x = int(x)
theList.append(x)
print("List =", theList)
return theList
这是我从中提取数据的文本文件:
9
7
1
3
2
5
4
我的预期输出应为:
List =[9,7,1,3,2,5,4]
然而,当我运行此函数时,我收到以下错误:
Traceback (most recent call last):
File "H:/CSCI-141/Week 7 Work/perk.py", line 47, in <module>
main()
File "H:/CSCI-141/Week 7 Work/perk.py", line 44, in main
perk_sort(file_open())
File "H:/CSCI-141/Week 7 Work/perk.py", line 17, in file_open
x = int(x)
ValueError: invalid literal for int() with base 10: ''
如果有人能告诉我为什么会收到此错误以及如何修复我的代码,我将非常感激!谢谢!
答案 0 :(得分:1)
您可能正在尝试在空行上应用int()。 您可以使用file.readlines()获取所有行,然后轻松地迭代它们。
试试这个:
def file_open():
filename = "PATH TO YOUR FILE"
fob = open(filename, 'r')
lines = fob.readlines()
final_list = []
for line in lines:
final_list.append(int(line))
print "List: %s" % final_list