【问题标题】:Appending a file that contains a list附加包含列表的文件
【发布时间】:2019-07-22 21:37:45
【问题描述】:

所以我目前正在自学python,我有以下任务: 编写一个python程序,创建一个里面有数字1到10的文件。

读取此文件并将内容打印回给用户。

现在要求用户输入一个数字以附加到文件的末尾,并将数字附加到文件中。

关闭文件。

我对前两部分和最后一部分没问题,但不确定是否要附加文件。

我得到的错误是“'str'对象没有属性'append'”

我希望将用户的输入附加到文件中,但这样做时出现错误。

任何帮助将不胜感激。我当前的代码是:

file1 = open("file1", "w")
r = range(10)
list1 = [*r]
file1.write(str(list1))
file1 = open("file1", "a")
a = int(input("enter the value of number: "))
file1 = open("file1", "r")
for line in file1:
    line.append(a)
    print(line)

【问题讨论】:

  • 由于某种原因我无法上传我的代码,所以我将其添加为评论。
  • file1 = open("file1","w") ------ r = range(10) #编写python程序创建编号为1-10的文件----- -- list1 =[*r] ------ file1.write(str(list1)) ------ file1 = open("file1", "a") ------ a = int (input("输入数字的值")) ------ file1 = open("file1", "r") ------ for line in file1: ------ line.append (a) ------ print(line) ------- 我添加了破折号,所以更容易看到格式

标签: python-3.x


【解决方案1】:

要附加到文件,您需要使用附加属性a+ 打开。 a 表示如果文件存在则打开文件并开始写入文件末尾,+ 标志告诉它如果文件不存在则创建文件:

newContent = "This will be appended to the end of the file.\n"
file = open("myFile.txt", "a+")
file.write(newContent)

【讨论】:

    【解决方案2】:

    您正在尝试追加到您正在迭代的 str 。无需迭代,因为您只想在文件末尾追加一次。打开后运行以下行:

    file1 = open("file1", "a")
    file1.write(a)
    

    【讨论】:

      【解决方案3】:

      尝试使用with 打开文件并使用a+ insted of a

      `with open("file1","w") as file1:
           list1 =list[range(10)]
           file1.write(str(list1))
       with open("file1", "a+") as file1:
           a = int(input("enter the value of number"))
           file1.write(a)`
      

      【讨论】:

        猜你喜欢
        • 2021-12-16
        • 1970-01-01
        • 2015-08-03
        • 1970-01-01
        • 2022-12-06
        • 2019-08-01
        • 2019-05-14
        • 2013-05-20
        • 1970-01-01
        相关资源
        最近更新 更多