‘tuple’对象没有属性’read’。

huangapple go评论62阅读模式
英文:

'tuple' object has no attribute 'read'

问题

我正在尝试创建一个程序,该程序将从我的计算机上的文件中读取内容。
该文件仅包含在括号内的门牌号,从1到150。

错误出现在第6行。 print(file.read())

# opening_a_file.py

file = "This PC/C:/Python Programming/Doors.txt","r"

print("read function: ")
print(file.read())
print()

file.seek(0)

我尝试重命名文件的绝对路径。
我还编辑了第3行,以将其更改为如下所示:

file = open("This PC/c:/Python Programming/Doors.txt","r")

但那并没有起作用。

英文:

I am trying to create a program that will read from a file on my computer.
The file consists of simply door numbers from 1-150 within a bracket.

The error returns at line 6. print(file.read())

#opening_a_file.py

file = "This PC/C:/Python Programming/Doors.txt","r"

print("read function: ")
print(file.read())
print()

file.seek(0)

I tried renaming the file absolute path.
I edited line 3 as well to read as:

file = open("This PC/c:/Python Programming/Doors.txt","r")

but that did not work.

答案1

得分: 0

This is because the variable file is a tuple. That is what happens when you define it in tuple format: var = value1, value2

So, in your case, you want a file object, so you need to do this:

file = open("C:/Python Programming/Doors.txt","r")

<br>

For the sake of the answer, here is the full code sum-up:

file = open("C:/Python Programming/Doors.txt","r")

print("read function: ")
print(file.read())
print()

file.seek(0)
英文:

This is because the variable file is a tuple. That is what happens when you define it in tuple format: var = value1, value2

So, in your case, you want a file object, so you need to do this:

file = open(&quot;C:/Python Programming/Doors.txt&quot;,&quot;r&quot;)

<br>

For the sake of the answer, here is the full code sum-up:

file = open(&quot;C:/Python Programming/Doors.txt&quot;,&quot;r&quot;)

print(&quot;read function: &quot;)
print(file.read())
print()

file.seek(0)

huangapple
  • 本文由 发表于 2023年7月17日 12:01:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76701413.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定