繁体   English   中英

在文件行之前添加文本的更有效,更通用的方法?

[英]More efficient and general way to prepend text before lines of a file?

我是python的新手。 在一项任务中,我必须在特定行之前添加一个字符。例如,在我的文本文件中,

名称

是我必须添加或删除的固定线路; 基于标志

hey : see
;Name:blah
;Surname:blah

这是我为相同代码编写的代码……它足够有效吗? 我们可以提高写作效率吗?

名和姓

作为参数,我的意思是将关键字作为要添加到的函数的参数

;

def changefile(filepath,flag):
   # flag = 1
    final = ""
    with open(filepath) as content:
        for line in content:
            if flag==1:
                if line.split(":")[0]==";Name" or line.split(":")[0]==";Surname":
                    final += line[1:]
                else:
                    final += line
            else:
                if line.split(":")[0]=="Name" or line.split(":")[0]=="Surname":
                    final += ";"
                final += line
    f = open(filepath, 'r+')
    f.truncate()
    f.write(final)
    f.close()


changefile("abc.txt",0)

我经常戳它,并借用了martineau的想法,最终得出以下结论:

def change_file(filepath, add_comment, trigger_words):

    def process(line):
        line_word = line.lstrip(';').split(':')[0]

        if line_word in trigger_words:
            if add_comment:
                line = line if line.startswith(';') else ';' + line
            else:
                line = line.lstrip(';')

        return line


    with open(filepath) as f:
        content = [process(line) for line in f]


    with open(filepath, 'r+') as f:
        f.truncate()
        f.write(''.join(content))


change_file('abc.txt', add_comment=True, trigger_words=["sys", "netdev"])

主要的“不错”位(我喜欢)使用列表推导[process(line) for line in f] ,因为它消除了整个final = ''; final += blah final = ''; final += blah安排。 它处理每一行,这就是输出。

我已经更改了flag所以现在不再显示“ 标志是0或1 ”(这是什么意思?),而是显示“ add_comment是True还是False ”,以更清楚地指示其作用。

就效率而言,可能会更好; (将“ trigger_words”设置为一个集合,以使测试成员资格更快,更改其标准化每一行以进行测试的方式); 但是,如果您正在处理一个小文件,那么Python的速度就不会足够快,而如果您正在处理一个大文件,则IO受限制的可能性大于CPU受限制的可能性。

在此处在线尝试: https : //repl.it/CbTo/0 (它读取并打印结果,但不尝试保存)。

(注意: .lstrip(';')将删除该行开头的所有分号,而不仅仅是一个分号。我假设只有一个)。


从评论中编辑。 这是一个可以处理SQL Server UTF-16安装文件而不会弄乱它的版本,但是我不知道一个适用于所有文件的常规修复程序。 请注意,这将读取文件作为特定的数据编码,并写入具有特定数据的二进制文件。 并将SQL ini格式的拆分更改为= 并且不会truncate因为w模式可以做到这一点。

import codecs

def change_file(filepath, add_comment, trigger_words):

    def process(line):
        line_word = line.lstrip(';').split('=')[0]

        if line_word in trigger_words:
            if add_comment:
                line = line if line.startswith(';') else ';' + line
            else:
                line = line.lstrip(';')

        return line


    with codecs.open(filepath, encoding='utf-16') as f:
        content = [process(line) for line in f]

    with codecs.open(filepath, 'wb', encoding='utf-16') as f:
        f.write(''.join(content))


change_file('d:/t/ConfigurationFile - Copy.ini', add_comment=True, trigger_words=["ACTION", "ENU"])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM