【问题标题】:python: How to change string in .txt file with inputpython:如何使用输入更改.txt文件中的字符串
【发布时间】:2017-09-15 15:57:30
【问题描述】:

所以我坚持使用此代码,重点是您输入汽车名称和要租的汽车数量,但我可以弄清楚如何在您租车后更改 .txt 文件中的字符串

def rental():
with open('cars.txt', 'r') as file:   # cars.txt example: 
                                      # bmw:320:red:new:6
        name = input('Car name: ')
        for line in file:
            s = line.split(':')`enter code here`
            if name == s[0] :
                amount = eval(input('Amount of cars'))
                if amount > int(s[4]):
                    print('Amount is too big')

                else:
                    t = str(int(s[4])-int(kolicina))
                    line.replace(s[4], t)           
        else:
            print('Car does not exist') 

【问题讨论】:

标签: python arrays string file


【解决方案1】:

如果您使用 'r' 调用 open,它将处于只读模式,因此如果您希望能够写入文件,请使用 'r+',如下所示:open('cars.txt', 'r+')。 此外,line.replace 将返回字符串的副本,而不是替换文件中的行。 要替换它,最简单的方法就是读入所有内容,更改要更改的行,然后再次写出。否则你也可以使用linecache 模块再次直接跳转到正确的行。 如果可能的话,我建议在程序开始时读取文件,并在程序运行时将所有信息保存在 RAM 中,仅在最后(或明确要求这样做时)将其写入文件,因为文件访问很慢。

【讨论】:

    猜你喜欢
    • 2020-10-28
    • 1970-01-01
    • 2021-11-03
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    相关资源
    最近更新 更多