首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python:如何删除注释行并在同一个文件上写入?

问Python:如何删除注释行并在同一个文件上写入?
EN

Stack Overflow用户
提问于 2016-07-29 12:53:33
回答 2查看 1.4K关注 0票数 1

我有一个注释文件列表,其中需要删除该文件(#)中的注释行,并需要在该文件上写入。

注释文件:

代码语言:javascript
复制
#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}

我所写的删除文件中注释行的代码?

代码:

代码语言:javascript
复制
>>> 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
}

我尝试使用上述两种方法--打印输出返回正确,但无法再次在同一文件上写入。

文件中的输出:

代码语言:javascript
复制
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}

预期输出:

代码语言:javascript
复制
 cat commentfile.txt
 define host {
                use             template
                host_name       google_linux
                address         192.168.0.12
        }

我甚至尝试过正则表达式方法,但没有在同一个文件上进行编写。

RE方法:

代码语言:javascript
复制
for line in file:
           m = re.match(r'^([^#]*)#(.*)$', line)
           if m:
              continue

有什么提示会有帮助吗?

EN

回答 2

Stack Overflow用户

发布于 2016-07-29 12:58:43

我不认为您可以将行写到正在循环的文件中,您需要将代码写到另一个文件中,您可以在循环后将其移到原始文件上。

或者,您可以将所有行读入内存,关闭并重新打开文件,并使用新处理的行对行进行写入。

票数 0
EN

Stack Overflow用户

发布于 2016-07-29 13:21:59

一些伪码

在read中打开一个新文件,在写模式下调用它temp循环并执行一些操作(删除注释,添加任何需要添加的内容),然后写入临时文件,关闭原始文件并删除它,然后将你的临时文件重命名为旧文件,这样就像

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38659425

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档