用fi编程Python

2024-06-12 15:11:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要帮助与下面的代码有关的问题。你知道吗

with open ("Premier_League.txt", "r+") as f:
        i= int(input("Please put in your result! \n"))
        data = f.readlines()
        print(data)
        data[i] = int(data[i])+1
        f.seek(0) # <-- rewind to the beginning
        f.writelines(str(data))
        f.truncate() # <-- cut any leftovers from the old version
        print(data)
        data[i] = str(data)

例如,如果文件 总理_联盟.txt包含:

1
2
3

当我运行程序choose i as 0 这给了我:

[2, '2\n', '3']

并将其保存到已存在的文件中(并删除旧内容) 但在那之后,我不能再运行程序了,它给了我这个:

ValueError: invalid literal for int() with base 10: "[2, '2\\n', '3']"

我的问题是:如何使新文件内容适合再次进入程序?


Tags: 文件the代码程序txt内容dataas
3条回答

遵循我的解决方案:

with open ("Premier_League.txt", "r+") as f:
        i= int(input("Please put in your result! \n"))
        # here strip wrong chars from input 
        data = f.readlines()
        print(data)
        # here added the str(..) conversion
        data[i] = str(int(data[i].strip())+1) + '\n'
        f.seek(0) # <  rewind to the beginning
        # the str(data) is wrong, data is a list!
        f.writelines(data)
        # I don't think this is necessary
        # f.truncate() # <  cut any leftovers from the old version
        print(data)
        # i think this is not necessary
        # data[i] = str(data)

我推荐这种方法:

with open('Premier_League.txt', 'r+') as f:
    data = [int(line.strip()) for line in f.readlines()] # [1, 2, 3]
    f.seek(0)

    i = int(input("Please put in your result! \n"))

    data[i] += 1  # e.g. if i = 1, data now [1, 3, 3]

    for line in data:
        f.write(str(line) + "\n")

    f.truncate()

f readlines()以字符串形式读取列表中的所有内容,如果您想将这些内容写回int

data=[]
with open ("Premier_League.txt", "r+") as f:
        i= int(input("Please put in your result! \n"))
        data = f.readlines()

with open ("Premier_League.txt", "w") as f:            
        for j in data:
            f.write(str(int(j)+1))
            #or do this to make it more clean,these lines are comments
            #j=int(j)+1
            #f.write(str(j))



         # <  cut any leftovers from the old version
print(data)

请注意,一旦打开一个文件,如果不关闭它,则写入的内容可能会丢失,无论您想对数据做什么,都必须使用第二种写入方法来完成

相关问题 更多 >