【问题标题】:AttributeError: '_io.TextIOWrapper' object has no attribute 'append'?AttributeError:“_io.TextIOWrapper”对象没有“附加”属性?
【发布时间】:2018-03-09 05:06:17
【问题描述】:

打印询问用户姓名

name = input("what is your name ")

file_name = str(input("What do you want to name this .txt file\n> "))
if file_name[-4:] != ".txt":
    file_name += ".txt"

问候他们

询问那里的姓名和员工姓名

print("Why hello",name,"now lets caculate that employee's next pay check")
def employees():
    emplist = []
    while True:
        names = input('What is the name of the employee')
        if names == 'done':
            break
        else:
            emplist += [names]
            print(emplist)
    pay(emplist)

要求按小时计酬

    def pay(emplist):


for person in emplist:
        print("now i need hourly pay of",person,)
        pay = float(input("> "))

询问他们的工作时间

print("now i need the hours worked by",person,)
    hours = float(input("> "))

计算工资

做数学题

if hours > 40:
        over = 1.50
        overtimeR = over * pay
        overtime = overtimeR * (hours-40)
        hours += 40
    else:
        overtime = 0

让他们做出不同的反应

尚未完成

if overtime > 0:
        hours2 = 40
        totalpay = (pay * hours2) + overtime
        pay_without_overtime = pay * hours2

else:
    totalpay = (pay * hours) + overtime

person_2 = ""

person_2 += person

info = ("Employee: "+str(person_2)+"\nTotal Hours: "+str(hours))




with open(file_name, 'a+')as file_data_2:
    file_data_2.append(info)





employees()

但它给了我错误

我该如何解决这个问题

AttributeError: '_io.TextIOWrapper' object has no attribute 'append'

【问题讨论】:

标签: python attributeerror


【解决方案1】:

当你用with open(file_name, 'a+') as file_data_2: 打开一个文件时,变量file_data_2 变成了一个类_io.TextIOWrapper 的实例,它确实没有这个属性。如果您想查看可用于您创建的任何变量的属性/方法,您可以在 Python 的交互模式下轻松完成。打开终端,运行你的 Python(在我的例子中是 Python 3):

$ python3

首先,打开您的文件并将其存储在一个变量中,类似于您在代码中所做的:

>>> file = open("sample.txt", 'a+')

变量file 现在是_io.TextIOWrapper 类的一个实例。您可以使用以下命令检查该类的可用方法:

>>> dir(file)

这是输出:

['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', 
'__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', 
'__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', 
'__init__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', 
'__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', 
'__sizeof__', '__str__', '__subclasshook__', '_checkClosed', 
'_checkReadable', '_checkSeekable', '_checkWritable', '_finalizing', 
'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno', 
'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 
'read', 'readable', 'readline', 'readlines', 'seek', 'seekable', 
'tell', 'truncate', 'writable', 'write', 'writelines']

如您所见,没有“附加”方法。但是,有“写”,我想这就是你需要的。

【讨论】:

    猜你喜欢
    • 2021-05-31
    • 2014-01-16
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-03
    • 2012-01-14
    相关资源
    最近更新 更多