如何使用seek和tell函数在python中编辑或更新记录文本文件的值

问题描述 投票:0回答:1

在第12类文件处理中,有一种使用seek和tell函数更新二进制文件的方法,但我需要它来处理文本文件

我尝试了一些方法,但最终出错了,任何人都可以帮助我。

def readFile():
    f=open(r'D:\Sri Sayee\project\gggg.txt','r+')
    for i in f:
        s=i.split()
        if s[0].lower()=='arvind':
           ......
            

此后我陷入困境。认为这是错误的任何人都可以帮助我。

python text-files file-handling
1个回答
0
投票

执行此操作的方式取决于数据在文件中的排列方式以及您可能想要进行的更改。

在此示例中,我们有一个文件,每行包含一个标记(名称)。

我们想要查找某个特定标记的任何/所有出现并将其替换为另一个标记。

SEARCH = "arvind"
REPLACE = "Sri Sayee Kathiravan"
FILENAME = "foo.txt"

update = False

with open(FILENAME, "r+") as data:
    tokens = list(map(str.rstrip, data))
    for i, token in enumerate(tokens):
        if token == SEARCH:
            tokens[i] = REPLACE
            update = True
    if update:
        data.seek(0)
        data.writelines(tokens)
        data.truncate() # this is critical if the change(s) would make the file smaller

另一种选择是将整个文件内容读入内存,然后使用 str.replace,但这可能会因部分匹配而导致不必要的修改

© www.soinside.com 2019 - 2024. All rights reserved.