首页 > 解决方案 > AttributeError: 'str' 对象没有属性 'read' 。打印时出错(filename.read())

问题描述

目前正在使用“Learn Python 3 the Hard Way”学习 Python。我在练习 17 中,并尝试将知识应用到我自己的项目中,同时完成练习。

该脚本应该从文件中读取 3 行,然后覆盖文件的内容,然后应该显示新内容。相反,我得到了这个错误。

**AttributeError: 'str' object has no attribute 'read'** 

我在这里第 70 行得到错误。

print(filename.read())

这是我所有的代码。

from sys import argv

script, fname = argv

# This variable just defines what the prompt should look it when
# a user is asked for input.
prompt=(" >>> ")

#This is just a greeting to myself.
print(f"""
-------------------------------------------

Hi {fname}!

If that's not your name you must have entered something else on the terminal.

This is a test project. I will enter in new things I learn to make
sure I'm committing them to memory. Please comment things so I don't
forgot what I'm doing. 

-------------------------------------------
""")

# This will ask the user to input the name of the file
# It will then confirm the filename.
# It will save the open(filename) command to the openFile variable
# Then I print the openFile variable using read()

print("What is the name of your sample file?",end='')
filename=input(prompt)

print(f"\nYou entered {filename} as the name of your file.\nHere are the contents of that file.\n")
openFile=open(filename)

print(openFile.read())

# This will close the variable which "filename" was assigned to but I don't
# think it actually closes the file.

openFile.close()

# This closes the file. I'm not certain if this is the right way to do it
# This might actually close the variable. Not the file. Tomato tomatoe?

# Here's the rest of your project
print(f"""

Great job so far {fname}! So we're going to work on writing to the file.

This will be tricky!

You will be asked to enter 3 lines of text. This will overwriting the existing data.

""")

# Here I'm going to assign filename to a variable called "target"
# I could use truncate to erase the contents of the file but I've read
# that simply opening a file in write mode will accomplish the same thing.

target = open(filename,'w')
line1 = input("Enter line 1:")
line2 = input("Enter line 2:")
line3 = input("Enter line 3:")
target.write(f"line\nline2\nline3")
target.close()


print(f"Great! You've updated {filename}!\nHere's the new content you entered\n")

# THIS IS WHERE THE ERROR IS OCCURING. NOT SURE WHY
print(filename.read())



print(f"Hi {fname}! What is your last name?",end='')
lname=input(prompt)

print(f"Hello {fname} {lname}! What is your address?",end='')
address=input(prompt)

print("What is your phone number?",end='')
phone=input(prompt)

val =input("Enter any value:")
print(f"You entered {val}.") #https://www.geeksforgeeks.org/taking-input-in-python/

print("What is your age?",end='')
age=input(prompt)

标签: python

解决方案


您必须打开它,并从文件描述符中读取,而不是文件名。正如你所做的那样

openFile=open(filename)

print(openFile.read())

推荐阅读