with open('my_file.py','r') as f:
lines=f.readlines()
with open('my_file.py','w') as f:
for line in lines :
if line.strip().startswith('#'):
lines.remove(line)
f.writelines(lines)
在這段代碼中我們首先讀出所有行,那麼對於任意行中,我們使用strip
(刪除空格),然後,如果該行已經開始與'#'
我們將其刪除。
此外,如果你有其他的代碼裏面您的評論,你可以使用regex
與re.sub
你可以做到這一點:
演示:
my_file.py:
################comment###########
{
'active': False,
'installable': True,
'test': [
# 'Test/purchase_order.yml'
# 'Test/purchase_picking.yml'
# 'Test/purchase_validation.yml'
# 'Test/sale_order.yml'
# 'Test/sale_validation.yml'
]
}
代碼:
import re
with open('test.txt','r') as f:
lines=f.readlines()
with open('test.txt','w') as f:
s=re.sub(r'#[\w \S]*','',''.join(lines))
f.writelines(s)
輸出:
{
'active': False,
'installable': True,
'test': [
]
}
放一點精力在你的題。一些格式和標點符號會很好。因爲它是不可讀的。 – interjay 2014-09-18 16:46:37
所有刪除的行都有'#'Test'模式嗎? – tdelaney 2014-09-18 17:03:44
你想刪除以'#'開頭的整行嗎?還是隻是**想刪除'#'並保持行的其餘部分不變? – 2014-09-18 17:28:45