Python Forum
Read text file, modify it then write back
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Read text file, modify it then write back
#1
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.
Reply
#2
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 welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags
Download my project scripts


Reply
#3
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.
Reply
#4
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='')
Reply
#5
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
Reply
#6
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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How can I write formatted (i.e. bold, italic, change font size, etc.) text to a file? JohnJSal 12 28,152 Feb-13-2025, 04:48 AM
Last Post: tomhansky
  How to write variable in a python file then import it in another python file? tatahuft 4 955 Jan-01-2025, 12:18 AM
Last Post: Skaperen
  How to read a file as binary or hex "string" so that I can do regex search? tatahuft 3 1,155 Dec-19-2024, 11:57 AM
Last Post: snippsat
  [SOLVED] [Linux] Write file and change owner? Winfried 6 1,567 Oct-17-2024, 01:15 AM
Last Post: Winfried
  python read PDF Statement and write it into excel mg24 1 999 Sep-22-2024, 11:42 AM
Last Post: Pedroski55
  Read TXT file in Pandas and save to Parquet zinho 2 1,281 Sep-15-2024, 06:14 PM
Last Post: zinho
  Pycharm can't read file Genericgamemaker 5 1,607 Jul-24-2024, 08:10 PM
Last Post: deanhystad
  Python is unable to read file Genericgamemaker 13 3,851 Jul-19-2024, 06:42 PM
Last Post: snippsat
  Delete file with read-only permission, but write permission to parent folder cubei 6 25,540 Jun-01-2024, 07:22 AM
Last Post: Eleanorreo
  Connecting to Remote Server to read contents of a file ChaitanyaSharma 1 3,352 May-03-2024, 07:23 AM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020