2014-09-18 57 views
0

有人能告訴我如何刪除一行註釋Python文件這樣的評論需要刪除數百個文件的Python這樣的:作爲刪除行評論python文件?

{ 
    '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' 
    ] 
} 

我搜索了這些類型在這個論壇的主題,但無法找到具體的事情因爲我需要的,謝謝您的關注

+2

放一點精力在你的題。一些格式和標點符號會很好。因爲它是不可讀的。 – interjay 2014-09-18 16:46:37

+0

所有刪除的行都有'#'Test'模式嗎? – tdelaney 2014-09-18 17:03:44

+0

你想刪除以'#'開頭的整行嗎?還是隻是**想刪除'#'並保持行的其餘部分不變? – 2014-09-18 17:28:45

回答

2

這裏是Kasra代碼的改進版本:

with open('my_file.py', 'r') as f: 
    lines = [line for line in f if line.strip()[0] != '#'] 

with open('my_file.py', 'w') as f: 
    f.writelines(lines) 

編輯

希望,這個版本的J古斯曼古斯曼的新要求,符合...

with open('my_file.py', 'r') as f: 
    lines = [line for line in f if not line.replace(' ','').lower().startswith("#'test/")] 

with open('my_file.py', 'w') as f: 
    f.writelines(lines) 
+0

謝謝毛羅,改進。 (我*真的需要睡一會兒:)) – 2014-09-18 17:21:39

+1

您可以刪除「.readlines()」部分,'[如果...中的行爲line ...]'避免使用文件內容創建額外的列表。像'r'\ s *#\ s *'Test /「這樣的正則表達式也可以。 – tdelaney 2014-09-18 18:33:31

+0

@tdelaney:好想法! – 2014-09-18 18:52:40

0
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(刪除空格),然後,如果該行已經開始與'#'我們將其刪除。

此外,如果你有其他的代碼裏面您的評論,你可以使用regexre.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': [ 





    ] 
} 
+3

那些行*不* * startswith(' 「)'。此外,您的語法不正確(缺少冒號,不正確的縮進)。 – jonrsharpe 2014-09-18 16:54:49

+0

感謝您的回覆,問題是如果我需要評論,如果實現該代碼,我會刪除評論,如果他們在我的python文件中,但這樣的評論; #'Test/sale_validation.yml',這是折舊需要刪除 – 2014-09-18 16:56:30

+0

@jonrsharpe我編輯代碼感謝提醒! – Kasramvd 2014-09-18 17:02:39

0

如果你有大量的行格式完全相同像你描述你可以使用Linux命令行上SED流編輯器:

這個命令只是一個替代的# '字符序列'

sed "s/# '/'/" /path/to/code/file.py 

當我將它傳遞您的例子中,它產生了以下內容:

{ 
    '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' 
    ] 
} 
+0

如果OP想要實際刪除這些行:'sed'/^[] *#/ d'' – 2014-09-18 17:15:21

+0

但是我們當然可以用Python來做這件事。 :) – 2014-09-18 17:51:49

+0

@ PM2Ring *腮紅* :-) – deau 2014-09-18 21:01:38