我有一个注释文件列表,我需要删除该文件中的注释行(#)并需要在同一个文件上写入。
评论文件:
#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
任何提示都会有帮助吗?
答案 0 :(得分:0)
我不认为你可以为你正在循环的文件写行,你需要写出一个不同的文件,你可以在循环后移动原始文件。
或者,您可以将所有行读入内存,关闭并重新打开文件,并使用新处理的行写入行
答案 1 :(得分:0)
一些伪代码
打开文件阅读 在写入模式下打开一个新文件称之为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)