2016-07-29 106 views
1

我有一个注释文件列表,我需要删除该文件(#)中的注释行,并且需要在同一个文件上写入。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 

任何暗示将是有益的?

+4

在读取文件时写入文件非常棘手。最好将整个文件读入内存,对其进行处理,然后一次性将其转储回文件中。这并不是那么大,所以消耗的内存并不重要。 – deceze

+1

如果它是一个小文件,请将整个文件读入内存,关闭文件,执行处理并将其写回。如果它是一个大文件,读取文件,进程,同时写入另一个文件,完成后,将临时文件重命名为原始文件。 – Vatine

+0

@deceze我在循环播放这些文件。但是有些文件也有2GB的配置数据,可以吗?如果我遵循你的方法。 –

回答

0

我不认为你可以写一行文件,你正在循环,你需要写出一个不同的文件,你可以在循环后移动原始文件。

或者,你可以阅读所有线路,内存,关闭并重新打开该文件,并写入了与新的加工线

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) 
相关问题