簡體   English   中英

在 Python 中將行附加到具有額外新行的現有文件

[英]Appending line to a existing file having extra new line in Python

我有一個文本文件

apple
banana

現在你仔細觀察最后有一個空白行。

什么時候追加

f = open("file.txt",'a')
f.write("orange")
f.close()

我得到輸出:

apple
banana

orange

我想在追加期間刪除中間的空白行。

我知道我可以手動轉到文件並刪除額外的新行。 但我想用python來做。 因此,每次出現空行時,它都會像這樣自動刪除:

apple
banana
orange

我搜索並嘗試過但無濟於事

利用:

f = open("file.txt",'ab')

'ab' 而不是只有 'a'

你不能,因為,追加模式正是這樣做的:它追加。 到換行符。 您必須讀取文件,在末尾刪除換行符,將其寫出然后追加。

或者,打開文件進行讀寫(模式'r+' ),尋找到最后,刪除換行符,然后繼續寫入。

我認為這可以解決問題:

f = open('file.txt', 'r+')
f.seek(-2, 2) # last character in file
if f.read(2) == '\n\n':
   f.seek(-1, 1) # wow, we really did find a newline! rewind again!
f.write('orange')
f.close()

一個簡單的解決方案是覆蓋整個文件,而不是就地修改它:

with open("file.txt") as input:
    # Read non-empty lines from input file
    lines = [line for line in input if line.strip()]
with open("file.txt", "w") as output:
    for line in lines:
        output.write(line)
    output.write("orange\n")

只要文件不太大,此代碼就可以正常工作。

您可以通過打開文件進行讀取和寫入、查找文件末尾的換行符數量、查找第一個尾隨換行符之后的位置並將行寫入附加到那里來更有效地做到這一點。 這更有效,但也需要更復雜的代碼,所以如果簡單的解決方案不夠快,我只會這樣做。

編輯:這是我對更有效的方法的看法:

with open("file.txt", "r+U") as f:
    try:
        f.seek(-1, 2)
        while f.read(1) == "\n":
            f.seek(-2, 1)      # go back two characters, since
                               # reading advances by one character
    except IOError:            # seek failed, so the file consists
        f.seek(0)              # exclusively of newline characters
    else:
        f.write("\n")          # Add exactly one newline character
    f.write("orange\n")        # Add a new line

這適用於任何數量的尾隨換行符,包括根本沒有或超過兩個。

這是另一種適用於該文件的解決方案:

with open('fruit.txt','rU+') as f:
    f.seek(-2,2)
    if(f.read(2) == "\n\n"):
        f.seek(-1,2)
    f.write('strawberry\n')

我們打開文件進行讀寫( 'r+' )。 然后我們從末尾開始尋找 2 個字節。 我們讀取這些字節。 (文件指針不在文件末尾)。 如果這些字節都是換行符,我們會后退一個字節。 然后我們寫我們的新數據。

編輯在更一般的情況下:

def goto_my_eof(f):
    """Position file pointer after last newline in file
       raises IOError if the file is "empty" (has no contents or only whitespace)
    """
    n=-1
    f.seek(n,2)
    mychar=f.read(1)
    #Step backward, one character at a time, looking for non-whitespace
    while not (mychar.strip()): 
        n-=1
        f.seek(n,2)
    mychar=f.read(1)
    #seek to the position after the non-whitespace position
    f.seek(n+1,2)
    #write one newline and continue.
    f.write('\n')

似乎工作(經過一些試驗)。 此外,這將刪除任何空格(不僅僅是換行符)。 將此與@SvenMarnach(他更優雅地使用tryexcept來捕獲錯誤)的答案結合起來會很棒。 對於我的函數,您可以將它包含在try / except中,如果出現except IOError則尋找位置 0(因為該函數假定文件中有一些非空白文本)。

我將編寫此代碼以向文件添加新行:

f=open('newfile.txt','a')

t=raw_input('write here something you like: ')

f.write(t+'\n')

然后讀取文件中的內容,啟動 shell 並輸入:

with open('newfile.txt','a') as f:
   for l in f:
       print l

這將打印文件中的所有內容。

我希望它能回答你的問題!!

有一個簡單的出路。 以原始格式寫入字符串並且不包含新空格。

 f=open('newfile.txt','a') 
 f.write(f"{your_string}")

這就對了。 文件中沒有新行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM