Python Forum

Full Version: Read text file, modify it then write back
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

The goal is to read text file, modify the content, then write this modified content to file:
Here is code that doesn't work:
import os
import re
file = 'aaa.txt'
with open(file, 'r') as f:
    lines = f.readlines()
    for line in lines:
        if re.match('\d\d\:\d\d', line):
            ind = lines.index(line)

    removed_lines_index = [i for i in range(ind)]
    for ind in sorted(removed_lines_index, reverse = True):
        del lines[ind]

    for line in lines:
        f.write(line)
The content of aaa.txt is something like this:
Output:
hfkjsahlhlksjakls zziiiiiiiiiii gggggggggggg hhhhhhhhhhhhh klfjlksjlfkvmfklm 00:00 kjsbnvjkfdkhfjkbksdf jdjajpofjojgaps jlkjlkajlvjlal
Any suggestions ?
Thanks.
If you're just wanting to remove the line with : in it you could do this
I'm using an in file and out file. Can be modified to just use one file.

in_file = 'Python/aaa.txt'
out_file = 'Python/aaa_copy.txt'

with open(in_file, 'r') as ifile, open(out_file, 'w') as ofile:
    for line in ifile.readlines():
        if ':' not in line:
            ofile.write(line)
I'm searching for some generic method, that is independent on what/how replace.
In short ... if the file aaa.txt contains "content A", how to replace it with "content B"
Sure, there is always method to create temporary file, put new content there, remove old file, then rename temporary file.
But I wonder if there is a method that would avoid creating a temporary file.
Using fileinput, it can be shortened to
import fileinput
for line in fileinput.input(('aaa.txt',), inplace=True):
    if not re.match('\d\d\:\d\d', line):
        print(line, end='')
Quote:Using fileinput, it can be shortened to
The scenario is a little bit different:
  • find a position that correspond to re.match criteria
  • remove whole content from the beginning until re.match
  • add something at the beginning
  • save
Filter lines as they are read. Close the file and reopen as write. Write the lines.
import re

pattern = re.compile(r'\d\d:\d\d')
with open('test.txt', 'r') as file:
    lines = [line for line in file if not re.match(pattern, line)]
with open('test.txt', 'w') as file:
    file.writelines(lines)
You could also open the file using 'r+' mode, skipping having to close and re-open the file, but why?
import re

pattern = re.compile(r'\d\d:\d\d')
with open('test.txt', 'r+') as file:
    lines = [line for line in file if not re.match(pattern, line)]
    file.truncate(0)
    file.seek(0)
    file.writelines(lines)