逐线阅读线显示attributeError

发布于 2025-02-08 17:18:20 字数 918 浏览 0 评论 0原文

我的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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦回旧景 2025-02-15 17:18:20

它必须为line.strip()不是compfile.strip()

compfile = open(input('path:'), 'r')
count = 0
for line in compfile:
    count += 1
    print("Line{}: {}".format(count, line.strip()))
compfile.close()

错误是因为您在文件对象上尝试使用strip()尝试使用strip()并且它没有属性strip

It has to be line.strip() not compfile.strip()

compfile = open(input('path:'), 'r')
count = 0
for line in compfile:
    count += 1
    print("Line{}: {}".format(count, line.strip()))
compfile.close()

The error is because you tried using strip() on the file object and it doesn't have the attribute strip

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文