簡體   English   中英

在python中搜索和替換文件中的行

[英]Search and replace lines in a file in python

我有一個自動生成的文件。 當按位運算符|時,我需要修改/編輯文件可以在 if 語句中找到,例如:

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

也需要修改:

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

因此,按位運算符需要更改為邏輯運算符,在條件語句中。

我到目前為止的代碼如下:

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) 

當前代碼每次出現時都會更改| || 無論在哪里| 在文件中。 所需的行為只是改變| || 在 if 語句中。

我該如何解決?

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) 

我會解決這個問題:

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) 

這應該有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM