简体   繁体   English

修改文本文件中的字符串

[英]Modify a string in a text file

In a file I have a names of planets: 在文件中,我有行星的名称:

sun moon jupiter saturn uranus neptune venus 太阳月亮木星土星天王星海王星金星

I would like to say "replace saturn with sun". 我想说“用太阳代替土星”。 I have tried to write it as a list. 我试图将其写为列表。 I've tried different modes (write, append etc.) 我尝试了不同的模式(写,追加等)

I think I am struggling to understand the concept of iteration, especially when it comes to iterating over a list , dict , or str in file. 我想我很难理解迭代的概念,尤其是当涉及遍历文件中的listdictstr时。 I know it can be done using csv or json or even pickle module. 我知道可以使用csv或json甚至pickle模块来完成。 But my objective is to get the grasp of iteration using for...loop to modify a txt file. 但是我的目标是使用for ... loop修改txt文件来掌握迭代的过程。 And I want to do that using .txt file only. 我只想使用.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())

Try this but keep in mind if you use string.replace method it will replace for example testsaturntest to testsuntest, you should use regex instead: 尝试此操作,但请记住,如果您使用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

This replaces the data in the file with the replacement you want and prints the values out: 这将用所需的替换替换文件中的数据,并打印出值:

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())

Replacing the lines in-file is quite tricky, so instead I read the file, replaced the files and wrote them back to the file. 替换文件中的行非常棘手,因此我改为读取文件,替换文件,然后将其写回到文件中。

If you just want to replace the word in the file, you can do it like this: 如果您只想替换文件中的单词,则可以这样操作:

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() 

I think its a clear guide :) You can find everything for this. 我认为这是一个清晰的指南:)您可以找到所有相关内容。

I have not tested your code but the issue with r+ is that you need to keep track of where you are in the file so that you can reset the file position so that you replace the current line instead of writing the replacement afterwords. 我尚未测试您的代码,但r+的问题是您需要跟踪文件中的位置,以便可以重置文件位置,以便替换当前行而不是编写替换后缀。 I suggest creating a variable to keep track of where you are in the file so that you can call myfile.seek() 我建议创建一个变量来跟踪您在文件中的位置,以便可以调用myfile.seek()

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

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