【问题标题】:"for" loop for reading line from a file is not working [closed]从文件中读取行的“for”循环不起作用[关闭]
【发布时间】: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 with statement,它将简化您的部分代码。

标签: python loops


【解决方案1】:

我建议在处理此类文件时使用with open() as

with open("bdata.txt", "r") as fh:
    for line in fh:
        # perform file operations

您的 "print(stripped_line)" 变量来自哪里,因为它似乎没有在您的示例中声明?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 2020-08-03
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    相关资源
    最近更新 更多