【发布时间】:2021-09-08 12:09:45
【问题描述】:
我正在尝试从 bdata.txt 读取文件。这里它正在正确打开文件但没有开始循环,您可以看到附加的屏幕,它没有打印 log3,而是打印关于文件打开的确认。下面是代码。请指教
####### get file name
#fname = input("Bike Data File name: ")
try:
fh = open('bdata.txt')
except:
print("Not able to open file")
print(fh)
print("Log2")
counter=0
####### extract data
for line in fh:
print("Log3")
counter = counter+1
print(stripped_line)
fh.close()
print(counter)
print ("**********EOF***********")
【问题讨论】:
-
你打开的文件的实际内容是什么?你确定你打开了正确的文件吗?
-
你必须打印 line 而不是 stripped_line 我会说
-
您阅读了
line,但从未对它做任何事情。 -
你的代码应该在
NameErrorprint(stripped_line),因为stripped_line从未被定义。问题不可重现。 -
请了解the
withstatement,它将简化您的部分代码。