[英]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 语句中找到,例如:
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.在 if 语句中。
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.这应该有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.