逐线阅读线显示attributeError
我的python中的脱衣舞()显示出错误。 我从geeksforgeeks复制并粘贴了此代码:
# Python program to
# demonstrate reading files
# using for loop
L = ["Geeks\n", "for\n", "Geeks\n"]
# Writing to file
file1 = open('myfile.txt', 'w')
file1.writelines(L)
file1.close()
# Opening file
file1 = open('myfile.txt', 'r')
count = 0
# Using for loop
print("Using for loop")
for line in file1:
count += 1
print("Line{}: {}".format(count, line.strip()))
# Closing files
file1.close()
将其转变为:
compfile = open(input('path:'), 'r')
count = 0
for line in compfile:
count += 1
print("Line{}: {}".format(count,
compfile.strip()))
compfile.close()
但是它显示了此错误:
Traceback (most recent call last):
File "....", line 5, in <module>
print("Line{}: {}".format(count, compfile.strip()))
AttributeError: '_io.TextIOWrapper' object has no attribute 'strip'
My strip() in Python is showing an error.
I copied and pasted this code from GeeksForGeeks:
# Python program to
# demonstrate reading files
# using for loop
L = ["Geeks\n", "for\n", "Geeks\n"]
# Writing to file
file1 = open('myfile.txt', 'w')
file1.writelines(L)
file1.close()
# Opening file
file1 = open('myfile.txt', 'r')
count = 0
# Using for loop
print("Using for loop")
for line in file1:
count += 1
print("Line{}: {}".format(count, line.strip()))
# Closing files
file1.close()
Turned it into this:
compfile = open(input('path:'), 'r')
count = 0
for line in compfile:
count += 1
print("Line{}: {}".format(count,
compfile.strip()))
compfile.close()
But it's showing this error:
Traceback (most recent call last):
File "....", line 5, in <module>
print("Line{}: {}".format(count, compfile.strip()))
AttributeError: '_io.TextIOWrapper' object has no attribute 'strip'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它必须为
line.strip()
不是compfile.strip()
错误是因为您在文件对象上尝试使用
strip()
尝试使用strip()
并且它没有属性strip
It has to be
line.strip()
notcompfile.strip()
The error is because you tried using
strip()
on the file object and it doesn't have the attributestrip