【问题标题】:Replace a certain value at a certain place in a text file in Python在Python中的文本文件中的某个位置替换某个值
【发布时间】:2019-01-30 16:47:00
【问题描述】:

我想编写一些代码来替换文本文件 (thefile.txt) 中某行上的某个值。我已经寻找了很长时间的解决方案来解决我的问题,但没有找到。
这是我写的代码:

clist = [1, 2, 0, 0, 0, 0]
with open("thefile.txt", "w") as dataFile:
    for line in dataFile:
        (key, val1, val2 ,val3, val4, val5) = line.split()
        if key == clist[0]:                               #Find correct line
            line = line.replace(val1, clist[1])           #Replace the value I want, but not the others

我的文本文件如下所示:

1 0 0 0 13 0
2 9 4 5 2 3
3 0 0 4 0 0

由于某种原因,它不起作用。我仍然是 python 的初学者,所以我相信问题可能在于我试图以写入模式(line.split)“读取”文件。我不知道每行的 line.split 是否被视为阅读。

【问题讨论】:

    标签: python python-3.x list file


    【解决方案1】:

    这应该会有所帮助。在您的示例中,您没有将更新的内容写回文件。

    演示:

    clist = [1, 2, 0, 0, 0, 0]
    res = []
    with open("thefile.txt") as dataFile:                    #Read file
        for line in dataFile:
            (key, val1, val2 ,val3, val4, val5) = line.split()
            if int(key) == clist[0]:                               #Find correct line
                res.append(line.replace(val1, str(clist[1])))      #Replace content and append to res
            else:
                res.append(line)
    
    with open("thefile.txt", "w") as dataFile:                #Write back to file.
        for line in res:
            dataFile.write(line)
    

    【讨论】:

    • 没用,res中val1没有被clist[1]替换
    • 尝试:if int(key) == clist[0]: 也可以使用res.append(line.replace(val1, str(clist[1])))
    【解决方案2】:

    你有一个空输出,对吧?而且原来的文件现在应该也是空的吧?

    通过在w 模式下打开dataFile,您是在告诉系统打开它进行写入,如果存在则截断它。当您稍后尝试读取它时,该文件的长度为零,因为您只是在打开时截断了它。

    如果要读取文件,请打开它进行读取。 (“r”模式)。如果您需要更新文件,请打开它以添加数据(“a”模式)或更新模式(“+”变体,即“w+”或“r+”)。

    无论如何,如果您更新了输入文件,那么只要它是一个文本文件(或者通常是具有可变长度记录的文件),您将很难正确完成它。您最好的方法是编写一个适合更新内容的新文件,并在最后替换原始文件(如果需要)。

    【讨论】:

      【解决方案3】:

      原则上可以就地更新文本文件,但这很棘手且容易出错。它需要的是对文件的随机访问,而文本文件不是为随机访问而设计的。

      按照您的方式逐行读取文件(但将模式设置为'r' 进行读取),并将每一行(修改或未修改)写入您以'w' 模式打开的新文件写。

      【讨论】:

        猜你喜欢
        • 2015-12-15
        • 2015-01-30
        • 2018-07-09
        • 1970-01-01
        • 2018-11-14
        • 1970-01-01
        • 2017-06-06
        • 1970-01-01
        • 2018-09-02
        相关资源
        最近更新 更多