简体   繁体   中英

Python : delete a string from a line of a text file python

I am a python noob. Suppose I have a FRUITS.txt file containing

apple 8456./unmatched/sfhogh/weyurg/wiagieuw

mango 5456./unmatched/swagr/arwe/rwh/EJA/AEH

carrot 7861468./unmatched/def/aghr/arhe/det/aahe

pineapple 5674./unmatched/awghhr/wh/wh5q/ja/JAE

I need to delete word unmatched from all the lines of a text file.I tried line.strip command but it erases everything from the file.

You have to split the line in single values an get the last value with [-1]. Then you can replace the word "unmatched" (or whatever you want) by an empty string.

with open("fruits.txt", "r") as file:
    lines = file.readlines()

for line in lines:
    value = line.split(" ")[-1].replace("unmatched", "")
    print(value)

Reads file, does string replacement and writes to same file

with open('data.txt', 'r+') as f:  # Opens file for read/write
  s = f.read().replace(r' ./unmatched/', r' ./')
  f.seek(0)      # go back to beginning of file
  f.write(s)     # write new content from beginning (pushes original content forward)
  f.truncate()   # drops everything after current position (dropping original content)

Test

Input file: 'data.txt'

apple 8456 ./unmatched/sfhogh/weyurg/wiagieuw

mango 5456 ./unmatched/swagr/arwe/rwh/EJA/AEH

carrot 7861468 ./unmatched/def/aghr/arhe/det/aahe

pineapple 5674 ./unmatched/awghhr/wh/wh5q/ja/JAE

Output file: 'new_data.txt'

apple 8456 ./sfhogh/weyurg/wiagieuw

mango 5456 ./swagr/arwe/rwh/EJA/AEH

carrot 7861468 ./def/aghr/arhe/det/aahe

pineapple 5674 ./awghhr/wh/wh5q/ja/JAE

First you have to read in the contents of the file:

file = open("fruits.txt", 'r') # opening in read mode
file_contents = file.read()
file.close()

There are a variety of ways of removing the substring "unmatched". One way is to split the string of file contents using "unmatched" as a delimiter, and then turn it back into a string.

file_contents = "".join(file_contents.split("unmatched")

Then you just need to rewrite the file.

file = open("fruits.txt", 'w') # now opening in write mode
file.write( file_contents)
file.close()

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