簡體   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