简体   繁体   中英

Search and replace lines in a file in python

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?

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) 
with open('Text.txt','r') as f:
    file_data = f.readlines()


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
file_data_str = ''.join(file_data)

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

This should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM