I've a list of commented file where I need to remove the comment lines in that files(#) and need to write on that same file.
comment file:
#Hi this the comment
define host {
use template
host_name google_linux
address 192.168.0.12
}
#commented config
#ddefine host {
#d use template1
#d host_name fb_linux
#d address 192.168.0.13
#d}
The code I wrote to remove the comment line in a file ?
code:
>>> with open('commentfile.txt','r+') as file:
... for line in file:
... if not line.strip().startswith('#'):
... print line,
... file.write(line)
...
define host {
use template
host_name google_linux
address 192.168.0.12
}
>>> with open('commentfile.txt','r+') as file:
... for line in file:
... if line.strip().startswith('#'):
... continue
... print line,
... file.write(line)
...
define host {
use template
host_name google_linux
address 192.168.0.12
}
I tried using the above two methods the print output returns correct but could not able to write on the same file again.
Output in file:
cat commentfile.txt
#Hi this the comment
define host {
use template
host_name google_linux
address 192.168.0.12
}
#commented config
#ddefine host {
#d use template1
#d host_name fb_linux
#d address 192.168.0.13
#d}
Expected Output:
cat commentfile.txt
define host {
use template
host_name google_linux
address 192.168.0.12
}
I've even tried Regular expression method but didn't work to write on the same file.
RE method:
for line in file:
m = re.match(r'^([^#]*)#(.*)$', line)
if m:
continue
Any hint would be helpful ?