Home > OS >  Search and replace lines in a file in python
Search and replace lines in a file in python

Time:11-06

I have a file that was autogenerated. I need to modify/edit the file when the bit-wise operator | is found in an if statement for example:

  if ((x ==1) | (y==1))

Needs to be changed too:

   if ((x ==1) || (y==1))

So, the bitwise operator needs to be changed to a logical operator, only in a conditional statement.

The code I have so far is as follows:

with open('filename','r') as f:
    file_data = f.readlines()
file_data_str = ''.join(file_data)

for line in file_data:
    if line.lstrip().startswith('if') and ('|' in line):
           
            file_data_str = file_data_str.replace(' | ', ' || ')

with open('filename','w') as f:
    f.write(file_data_str) 

The current code changes every occurrence of | to || no matter where | is in the file. The desired behavior is to only change | to || in an if statement.

How do I fix this?

CodePudding user response:

with open('filename','r') as f:
    file_data = f.readlines()
file_data_str = ''.join(file_data)

for line in file_data:
    if line.lstrip().startswith('if') and ('|' in line):
            #the problem is here: with this statement you change all occurrences
            file_data_str = file_data_str.replace(' | ', ' || ')

with open('filename','w') as f:
    f.write(file_data_str) 

I would resolve with this:

with open('filename','r') as f:
    file_data = f.readlines()

for ii in range(len(file_data)):
    if file_data[ii].lstrip().startswith('if') and ('|' in line):
           
            file_data[ii]= file_data[ii].replace(' | ', ' || ')

file_data_str = ''.join(file_data)

with open('filename','w') as f:
f.write(file_data_str) 

CodePudding user response:

with open('Text.txt','r') as f:
    file_data = f.readlines()
file_data_str = ''.join(file_data)
i=0
while i in range(len(file_data)):
    for line in file_data:
        if file_data[i].lstrip().startswith('if') and ('|' in line):          
            file_data[i]= file_data[i].replace(' | ', ' || ')
    i =1

with open('Text.txt','w') as f:
    f.write(file_data_str)

This should work.

  • Related