0

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.

3 Answers 3

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

@DarryIG I don't want to generate a new text file for it.
@karkator--no problem, I updated my answer to overwrite the file.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.