0

I want to change some text in a file i have, but I can't find a proper way to delete a character from a file with python. Is it possible? For example I have a file which looks alot like this:

Marry has 10 carrots
Bob has 15 apples
Tom has 4 bananas

Now I want to change the numbers in the file, or even the fruits. I can read just the numbers but I can't remove them or overwrite them.

Singularity
  • 143
  • 12
  • 1
    Read the file, parse the information, change the information, and write out the data to the file in the same format. – poke May 27 '15 at 11:37

1 Answers1

7

Use fileinput with inplace=True to modify the file content:

import fileinput
import sys
for line in fileinput.input("test.txt",inplace=True):
    # replaces all occurrences of apples in each line with oranges
    sys.stdout.write(line.replace("apples","oranges"))

Input:

Marry has 10 carrots
Bob has 15 apples
Tom has 4 bananas

Output:

Marry has 10 carrots
Bob has 15 oranges
Tom has 4 bananas

Use re to avoid matching substrings:

import fileinput
import sys
import re
# use word boundaries so we only match "apples"  
r = re.compile(r"\bapples\b")
for line in fileinput.input("test.txt",inplace=True):
    # will write the line as is or replace apples with oranges and write
    sys.stdout.write(r.sub("oranges",line))

To remove all the last words:

import fileinput
import sys
for line in fileinput.input("test.txt",inplace=True):
    # split on the last whitespace and write everything up to that
    sys.stdout.write("{}\n".format(line.rsplit(None, 1)[0]))

Output:

Marry has 10
Bob has 15
Tom has 4

You can also use a tempfile.NamedTemporaryFile to write the updated lines to using any of the logic above, then use shutil.move to replace the original file:

from tempfile import NamedTemporaryFile
from shutil import move

with open("test.txt") as f, NamedTemporaryFile("w",dir=".", delete=False) as temp:
    for line in f:
        temp.write("{}\n".format(line.rsplit(None, 1)[0]))

# replace original file with updated content
move(temp.name,"test.txt")

You need to pass dir="." and delete=False so the file file won't be deleted when we exit the with and we can access the file with the .name attribute to pass to shutil.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321