簡體   English   中英

在Python中打開輸入和輸出文件

[英]Open a file for input and output in Python

我有以下代碼,旨在刪除文件的特​​定行。 當我運行它時,它會打印出目錄中的兩個文件名,然后刪除其中的所有信息。 我究竟做錯了什么? 我在Windows下使用Python 3.2。

import os

files = [file for file in os.listdir() if file.split(".")[-1] == "txt"]

for file in files:
    print(file)
    input = open(file,"r")
    output = open(file,"w")

    for line in input:
        print(line)
        # if line is good, write it to output

    input.close()
    output.close()

open(file, 'w')擦除文件。 為防止這種情況,請在r+模式下打開它(讀取+寫入/不擦除),然后立即讀取所有內容,過濾行並再次將其寫回。 就像是

with open(file, "r+") as f:
    lines = f.readlines()              # read entire file into memory
    f.seek(0)                          # go back to the beginning of the file
    f.writelines(filter(good, lines))  # dump the filtered lines back
    f.truncate()                       # wipe the remains of the old file

我認為good是一個函數,告訴我是否應該保留一條線。

如果您的文件適合內存,最簡單的解決方案是打開文件進行讀取,將其內容讀取到內存,關閉文件,打開文件進行寫入並將過濾后的輸出寫回:

with open(file_name) as f:
    lines = list(f)
# filter lines
with open(file_name, "w") as f:      # This removes the file contents
    f.writelines(lines)

由於您不是在進行讀寫操作,因此這里不需要像"r+"這樣的高級文件模式,只能編譯。

如果文件不適合內存,通常的方法是將輸出寫入新的臨時文件,並在處理完成后將其移回原始文件名。

一種方法是使用fileinput stdlib模塊。 那么你不必擔心打開/關閉和文件模式等...

import fileinput
from contextlib import closing
import os

fnames = [fname for fname in os.listdir() if fname.split(".")[-1] == "txt"] # use splitext
with closing(fileinput.input(fnames, inplace=True)) as fin:
    for line in fin:
        # some condition
        if 'z' not in line: # your condition here
            print line, # suppress new line but adjust for py3 - print(line, eol='') ?

當使用inplace inplace=True - fileinput將stdout重定向到當前打開的文件。 創建具有默認“.bak”擴展名的文件備份,如果需要,可能會有用。

jon@minerva:~$ cat testtext.txt
one
two
three
four
five
six
seven
eight
nine
ten

運行上面的條件not line.startswith('t')

jon@minerva:~$ cat testtext.txt
one
four
five
six
seven
eight
nine

當您打開要寫入的文件時,您將刪除所有內容。 您不能同時打開和寫入文件。 改為使用open(file,"r+") ,然后在寫入任何內容之前將所有行保存到另一個變量。

您不應該同時打開同一個文件進行讀寫。

“w”表示為寫作創建一個空。 如果該文件已存在,則其數據將被刪除。

因此,您可以使用不同的文件名進行編寫。

暫無
暫無

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

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