繁体   English   中英

修改文本文件中的字符串

[英]Modify a string in a text file

在文件中,我有行星的名称:

太阳月亮木星土星天王星海王星金星

我想说“用太阳代替土星”。 我试图将其写为列表。 我尝试了不同的模式(写,追加等)

我想我很难理解迭代的概念,尤其是当涉及遍历文件中的listdictstr时。 我知道可以使用csv或json甚至pickle模块来完成。 但是我的目标是使用for ... loop修改txt文件来掌握迭代的过程。 我只想使用.txt文件来实现。

with open('planets.txt', 'r+')as myfile:
    for line in myfile.readlines():
        if 'saturn' in line:
            a = line.replace('saturn', 'sun')
            myfile.write(str(a))
        else:
            print(line.strip())

尝试此操作,但请记住,如果您使用string.replace方法,它将替换例如testsaturntest到testsuntest,则应改用regex

In [1]: cat planets.txt
saturn

In [2]: s = open("planets.txt").read()

In [3]: s = s.replace('saturn', 'sun')

In [4]: f = open("planets.txt", 'w')

In [5]: f.write(s)

In [6]: f.close()

In [7]: cat planets.txt
sun

这将用所需的替换替换文件中的数据,并打印出值:

with open('planets.txt', 'r+') as myfile:
    lines = myfile.readlines()

modified_lines = map(lambda line: line.replace('saturn', 'sun'), lines)

with open('planets.txt', 'w') as f:
    for line in modified_lines:
        f.write(line)

        print(line.strip())

替换文件中的行非常棘手,因此我改为读取文件,替换文件,然后将其写回到文件中。

如果您只想替换文件中的单词,则可以这样操作:

import re
lines = open('planets.txt', 'r').readlines()
newlines = [re.sub(r'\bsaturn\b', 'sun', l) for l in lines]
open('planets.txt', 'w').writelines(newlines)
f = open("planets.txt","r+")
lines = f.readlines() #Read all lines

f.seek(0, 0); # Go to first char position

for line in lines: # get a single line 
    f.write(line.replace("saturn", "sun")) #replace and write

f.close() 

我认为这是一个清晰的指南:)您可以找到所有相关内容。

我尚未测试您的代码,但r+的问题是您需要跟踪文件中的位置,以便可以重置文件位置,以便替换当前行而不是编写替换后缀。 我建议创建一个变量来跟踪您在文件中的位置,以便可以调用myfile.seek()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM