删除一行注释的python文件?

时间:2014-09-18 16:45:22

标签: python file

有人可以告诉我如何删除一行评论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' 
    ]
}

我在这个论坛中搜索了这些类型的主题,但找不到我需要的具体内容,谢谢你的关注

3 个答案:

答案 0 :(得分: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 Guzman Guzman的新要求......

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)

答案 1 :(得分: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': [





    ]
}

答案 2 :(得分: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' 
    ]
}