简体   繁体   中英

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. I know it can be done using csv or json or even pickle module. But my objective is to get the grasp of iteration using for...loop to modify a txt file. And I want to do that using .txt file only.

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:

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. I suggest creating a variable to keep track of where you are in the file so that you can call myfile.seek()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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