drawn_inward
drawn_inward

Reputation: 25

Python: Read in specific lines from a file and replace a specific character on those lines and save file

New to python and can't find the answer for this problem. I have a file similar to this:

@BNNDSIJHF
ABCDABCDAB
&
*&ABDA&&#

There are four lines of data for an object. There are 1000's of objects in the file, so there are 4*objects in the file. I need to replace all the Bs with Xs, but only on line 2 of each object. Ex.

@BNNDSIJHF
AXCDAXCDAX
&
*&ABDA&&#

Even though the last line of the object has Bs in it, they don't get replaced. Here's what I've tried:

import sys
import os
def open_and_replace(filename):
with open(filename) as read_file:
    temp = open("/tmp/temp.txt","w")
    for index,line in enumerate(read_file,1):
        if index == 2:
            temp.write(line.replace('B', 'X'))
            index=index+4
        else:
            temp.write(line.strip() + "\n")
    temp.close()
os.rename("/tmp/temp.txt",filename)
for file_name in sys.argv[1:]:
open_and_replace(file_name)

This replaces the all the B's in the file past line 2. Any help would be appreciated!

Upvotes: 1

Views: 55

Answers (2)

PMende
PMende

Reputation: 5460

You should change the if index == 2 statement to be if index % 4 == 2, and remove the index=index+4 line.

Upvotes: 1

rafaelc
rafaelc

Reputation: 59274

IIUC, if you have a list of lines with no whitespaces

[x for x in f.readlines() if x.strip()]

such as

['@BNNDSIJHF',
 'ABCDABCDAB',
 '&',
 '*&ABDA&&#',
 '@BNNDSIJHF',
 'ABCDABCDAB',
 '&',
 '*&ABDA&&#']

You can just use a for loop starting at 2nd line with a step of 4, which is the fixed length of every object.

for i in range(1, len(ll),  4):
    ll[i] = ll[i].replace('B', 'X')

Then just '\n'.join save it back to a file

Upvotes: 2

Related Questions