python正则表达式和编写文件查询
我有一个问题,关于在使用regex和loop进行更改后如何在一个文件上写入 我想更改“python正则表达式和编写文件查询,python,regex,Python,Regex,我有一个问题,关于在使用regex和loop进行更改后如何在一个文件上写入 我想更改“text align:left”的“left”在“p.FM_table_cell_body*{”下。 (*表示数字) 这是一个css示例文件,如下所示: file = '''p.FM_table_cell_body1 { margin-left:0.000pt; margin-right:0.000pt; text-align:left; text-indent:0.000pt;
text align:left”的“left
”代码>在“p.FM_table_cell_body*{
”下。
(*
表示数字)
这是一个css示例文件,如下所示:
file = '''p.FM_table_cell_body1 {
margin-left:0.000pt;
margin-right:0.000pt;
text-align:left;
text-indent:0.000pt;
}
p.FM_table_cell_body2 {
margin-left:0.000pt;
margin-right:0.000pt;
text-align:left;
text-indent:0.000pt;
}
p.FM_table_cell_body3 {
margin-left:0.000pt;
margin-right:0.000pt;
text-align:left;
text-indent:0.000pt;
}'''
这就是我正在尝试的
import re
for A in range(2,4) : # these numbers are just example, they can be changed.
print(A)
with open ("C:\\TEST\\HTML\\Output_sample1\\Responsive HTML5\\Output_test.css","wt",encoding="utf-8") as file_new :
new_content = re.sub(r"(p\.FM_table_cell_body" + str(A) + " {[^}]+text-align:)left", r"\1center", file)
file_new.write(str(new_content))
但此代码仅更改“FM_table_cell_body 3
”下的“text align:center;”
”
我想要的输出如下:
file_new = '''p.FM_table_cell_body1 {
margin-left:0.000pt;
margin-right:0.000pt;
text-align:left;
text-indent:0.000pt;
}
p.FM_table_cell_body2 {
margin-left:0.000pt;
margin-right:0.000pt;
text-align:center; # 'left' is changed to 'center'
text-indent:0.000pt;
}
p.FM_table_cell_body3 {
margin-left:0.000pt;
margin-right:0.000pt;
text-align:center; # 'left' is changed to 'center'
text-indent:0.000pt;
}'''
我应该修改哪一部分?每次循环中,您只是在编写当前替换,覆盖了上一次迭代中所做的操作
您应该在循环中每次更新new_content
字符串,然后在最后写入文件
import re
new_content = file
for A in range(2,4) : # these numbers are just example, they can be changed.
print(A)
new_content = re.sub(r"(p\.FM_table_cell_body" + str(A) + " {[^}]+text-align:)left", r"\1center", new_content)
with open ("C:\\TEST\\HTML\\Output_sample1\\Responsive HTML5\\Output_test.css","wt",encoding="utf-8") as file_new :
file_new.write(str(new_content))
哦,巴玛!太棒了!我实际上是被绊倒了,但你救了我,谢谢你。