我已经获得了一个文本文件,其中包含
格式的名称列表ID Year CourseCode OtherNames LastName 例如 1234567 5 X500 Xrin Stack
现在我已经编写了一个代码来打开文件,我有两个功能 一个函数需要将数据存储到元组中(在列表中) 第二个函数需要格式化元组,即固定宽度。
但是,我为什么我的代码无法正常工作,我感到有些困惑。我认为这与在文本正文中调用函数有关。
def student(l,reg,year,degree,other_name,last_name):
if not isinstance(reg, int) or \
not isinstance(year, int) or \
not isinstance(degree, str) or \
not isinstance(other_name, str) or \
not isinstance(last_name, str) :
print("Invalid string argument")
elif 0<=year<=4:
l.append((reg,year,degree,other_name,last_name))
else: print("Invalid year")
return l
def printStud(student):
reg,year,degree,other_name,last_name = student
reg=int(reg)
year=int(year)
fullName=last_name+ ", " + other_name
#thisYear="Year" + str(year)
print(format(fullName, "<32s")+format(reg,"<7d")+format(degree,">6s")+format(year,">6s"))
try:
filename = input("Enter the name of the file to open: ") + ".txt"
f = open(filename,"r")
readFile = f.readlines()
f.close()
for line in readFile:
print(printStud(student))
except FileNotFoundError:
print("Failed to open",filename)
所以我想做的是 打开文件,将列表中的每个项目存储为元组(多行,因此为什么使用for循环读取行) 然后格式化固定宽度的元组,但我有一个问题,在某处。 目前我的代码错误显示:
Traceback (most recent call last):
File "C:\Users\TOSHIBA\Documents\exercise1.py", line 35, in <module>
print(printStud(student))
File "C:\Users\TOSHIBA\Documents\exercise1.py", line 22, in printStud
reg,year,degree,other_name,last_name = student
TypeError: 'function' object is not iterable
答案 0 :(得分:1)
def printStud(student):
reg,year,degree,other_name,last_name = student.strip().split(" ")
reg=int(reg)
year=int(year)
fullName=last_name+ ", " + other_name
#thisYear="Year" + str(year)
print(format(fullName, "<32s")+format(reg,"<7d")+format(degree,">6s")+format(year,">6s"))
这应解决问题,因为文件具有相同的结构,即所有信息都用空格分隔,每行有5个字。
e.g。
1234 1990 B.Tech Foo Bar
1235 1991 B.Tech Bob Alice
如果您有其他分隔符,则更新然后使用正确的分隔符更新reg,year,degree,other_name,last_name = student.strip().split(" ")
或者可以使用try catch。
答案 1 :(得分:0)
使用Python迭代文件内容的优先方法是使用await
块并迭代文件本身,如下所示:
with
我认为错误本身源于您正在调用try:
filename = input("Enter the name of the file to open: ") + ".txt"
with open(filename) as f:
for line in f:
print(printStud(line))
这一事实,其中student是您之前定义的函数的名称。我将其更改为文件中行的内容,这可能是您真正想要的。试试这个并告诉我它是否有效。