J Guzman Guzman
J Guzman Guzman

Reputation: 13

as removing a line commented python file?

Could someone tell me how to delete a line commented a python file such comments need to delete hundreds of files Python like this:

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

I searched for these types of topics in this forum but can not find anything specific as I need, thank you for your attention

Upvotes: 0

Views: 128

Answers (3)

PM 2Ring
PM 2Ring

Reputation: 55489

Here's an improved version of Kasra's code:

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)

Edit

Hopefully, this version complies with J Guzman Guzman's new requirements...

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)

Upvotes: 2

Kasravnd
Kasravnd

Reputation: 107337

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)

In this code first we read all lines then for any line we use strip (delete spaces) and then if the line have been started with '#' we delete it .

Also if you have your comment inside other codes you can use regex and with re.sub you can do it:

Demo:

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

your code :

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)

output:

{
    'active': False, 
    'installable': True, 
    'test': [





    ]
}

Upvotes: 0

deau
deau

Reputation: 1223

If you have lots of lines formatted exactly like what you have described you can use the SED stream editor on the linux command line:

This command replaces the character sequence of # ' with just a ':

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

When I pass it your example code it yields the following:

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

Upvotes: 0

Related Questions