我有一个注释文件列表,我需要删除该文件(#)中的注释行,并且需要在同一个文件上写入。Python:如何删除注释行并写入同一个文件?
注释文件:
#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}
我写删除一个文件中的注释行的代码?
代码:
>>> 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
}
我尝试使用上述两种方法的打印输出回到正确的,但能不能在同一个文件写一遍。
输出文件:
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}
预期输出:
cat commentfile.txt
define host {
use template
host_name google_linux
address 192.168.0.12
}
我甚至试过正则表达式的方法,但没有工作在同一个文件写入。
RE方法:
for line in file:
m = re.match(r'^([^#]*)#(.*)$', line)
if m:
continue
任何暗示将是有益的?
在读取文件时写入文件非常棘手。最好将整个文件读入内存,对其进行处理,然后一次性将其转储回文件中。这并不是那么大,所以消耗的内存并不重要。 – deceze
如果它是一个小文件,请将整个文件读入内存,关闭文件,执行处理并将其写回。如果它是一个大文件,读取文件,进程,同时写入另一个文件,完成后,将临时文件重命名为原始文件。 – Vatine
@deceze我在循环播放这些文件。但是有些文件也有2GB的配置数据,可以吗?如果我遵循你的方法。 –