Reputation: 61
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.
Upvotes: 0
Views: 160
Reputation: 17166
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
Upvotes: 0
Reputation: 51
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()
Upvotes: 0
Reputation: 271
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)
Upvotes: 1