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


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
  What does .flush do? How can I change this to write to the file? Pedroski55 3 207 Apr-22-2024, 01:15 PM
Last Post: snippsat
  Last record in file doesn't write to newline gonksoup 3 435 Jan-22-2024, 12:56 PM
Last Post: deanhystad
  Recommended way to read/create PDF file? Winfried 3 2,899 Nov-26-2023, 07:51 AM
Last Post: Pedroski55
  write to csv file problem jacksfrustration 11 1,546 Nov-09-2023, 01:56 PM
Last Post: deanhystad
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,468 Nov-09-2023, 10:56 AM
Last Post: mg24
Question Special Characters read-write Prisonfeed 1 627 Sep-17-2023, 08:26 PM
Last Post: Gribouillis
  read file txt on my pc to telegram bot api Tupa 0 1,128 Jul-06-2023, 01:52 AM
Last Post: Tupa
  parse/read from file seperated by dots giovanne 5 1,124 Jun-26-2023, 12:26 PM
Last Post: DeaD_EyE
  Formatting a date time string read from a csv file DosAtPython 5 1,295 Jun-19-2023, 02:12 PM
Last Post: DosAtPython
  How do I read and write a binary file in Python? blackears 6 6,672 Jun-06-2023, 06:37 PM
Last Post: rajeshgk

Forum Jump:

User Panel Messages

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