我有一个注释文件列表,其中需要删除该文件(#)中的注释行,并需要在该文件上写入。
注释文件:
#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有什么提示会有帮助吗?
发布于 2016-07-29 12:58:43
我不认为您可以将行写到正在循环的文件中,您需要将代码写到另一个文件中,您可以在循环后将其移到原始文件上。
或者,您可以将所有行读入内存,关闭并重新打开文件,并使用新处理的行对行进行写入。
发布于 2016-07-29 13:21:59
一些伪码
在read中打开一个新文件,在写模式下调用它temp循环并执行一些操作(删除注释,添加任何需要添加的内容),然后写入临时文件,关闭原始文件并删除它,然后将你的临时文件重命名为旧文件,这样就像
fileVar = open(file, 'r')
tempFile = open(file, 'w')
for line in file:
# do your operations
#you could write at the same time
tempFile.write(linePostOperations)
fileVar.close()
os.remove(filePath)
tempFile.close()
os.rename(tempFileName, newFileName)https://stackoverflow.com/questions/38659425
复制相似问题