python - Python程序不会读取文本文件中的新行
问题描述
我正在尝试逐行读取文本文件,以便将信息存储到一些变量中,但它在文件结束之前捕获了一个错误。在执行 line = f.readline().strip() 时,程序拒绝读取文件中的下一行并发生此错误:
回溯(最近一次通话最后):
文件“/Users/JoCarbons/PycharmProjects/untitled/venv/Gestione.py”,第 48 行,在 main
line = f.readline().strip()
AttributeError:对象没有属性“readline”
这是主文件的一部分:
def main(self):
Veicoli = []
try:
f = open("veicoli.txt", "r")
line = f.readline().strip()
while (line != ''):
tok = line.split()
cod = int(tok[0])
tipo = tok[1]
targa = tok[2]
line = f.readline().strip()
if (tipo == "auto"):
tok = line.split()
cilindrata = int(tok[0])
diesel = bool(tok[1])
line = f.readline().strip()
modello = line
line = f.readline().strip()
marca = line
a = Auto(cod, tipo, targa, cilindrata, diesel, modello, marca)
Veicoli.append(a)
line = f.readline()
else:
#line = f.readline().strip()
categoria = line
line = f.readline().strip()
posti = int(line)
line = f.readline().strip()
modello = line
line = f.readline().strip()
marca = line
f = Furgone(cod, tipo, targa, categoria, posti, modello, marca)
line = f.readline().strip()
Veicoli.append(f)
f.close()
except IOError:
print("IO error found.")
except:
print("Unexpected error: ", sys.exc_info()[0])
raise
解决方案
试试这个简单的程序,它将打印文件中的每一行
f = open("demofile.txt", "r")
for x in f:
print(x)
推荐阅读
- sql - ClickHouse 中的枚举类型数组
- filtering - Excel - 工作表顶部的预选过滤对象
- docker - 谷歌浏览器需要更高版本才能运行集成测试
- jquery - ASP.net MVC 列表框在帖子中获取所有值
- git - 尝试更正我的 GitHub 子模块以将其删除并添加到根文件夹以进行提交
- react-native - React native Expo:创建了一个应用程序,在 chrome 的检查工具中它运行良好,但在移动设备上运行后它被放大了
- python - 如何删除与 pdf 对应文件同名的 excel 文件?
- ruby-on-rails - 如何覆盖 batch_action(ActiveAdmin) 并在那里传递对象?
- apache - .htaccess 将 domain.com/folder 重定向到外部网站而不更改 URL
- javascript - 为什么Element null vue js