簡體   English   中英

打開文件進行隨機寫入而不截斷?

[英]open file for random write without truncating?

在 python 中,您可以在打開文件進行操作時提供一些標志。 我對找到一個允許我在不截斷的情況下進行隨機寫入的組合感到有點困惑。 我要找的行為等價於C:不存在就創建,否則就open for write(不截斷)

open(filename, O_WRONLY|O_CREAT)

Python 的文檔令人困惑(對我來說): "w"將首先截斷文件, "+"應該表示更新,但"w+"無論如何都會截斷它。 有沒有辦法在不求助於低級os.open()接口的情況下實現這一目標?

注意: "a""a+"也不起作用(如果我在這里做錯了什么,請更正)

cat test.txt
eee

with open("test.txt", "a+") as f:
  f.seek(0)
  f.write("a")
cat test.txt
eeea

是不是append模式一定要寫到最后?

你可以用 os.open 做到這一點:

import os
f = os.fdopen(os.open(filename, os.O_RDWR | os.O_CREAT), 'rb+')

現在您可以在文件中間進行讀取、寫入、查找等操作。 它會創建文件。 在 Python 2 和 3 上測試。

你應該在rb+模式下打開。

with open("file", "rb+") as file:
    file.write(b"...")

在Python 2上,您可以使用r+代替文本模式,但您不應該因為它可以更改您編寫的文本的長度。

您應該嘗試讀取文件然后打開寫入模式,如下所示:

with open("file.txt") as reading:
    r = reading.read()
with open("file.txt", "w") as writing:
    writing.write(r)

根據討論Difference between modes a, a+, w, w+, and r+ in built-in open functiona模式的打開將始終寫入文件末尾,而不管任何干預 fseek(3) 或類似的。

如果你只想使用python內置function。我猜解決方案是先檢查文件是否存在,然后用r+模式打開。

例如:

import os
filepath = "test.txt"
if not os.path.isfile(filepath):
    f = open(filepath, "x") # open for exclusive creation, failing if the file already exists
    f.close()
with open(filepath, "r+") as f: # random read and write
    f.seek(1)
    f.write("a")

您需要使用"a"來追加,如果文件不存在,它將創建文件,如果存在則追加到它。

當您調用 write 方法時,指針會自動移至文件末尾,因此您無法使用 append 執行您想要的操作。

您可以檢查文件是否存在,然后使用fileinput.input和 inplace inplace=True在您想要的任何行號上插入一行。

import fileinput
import os


def random_write(f, rnd_n, line):
    if not os.path.isfile(f):
        with open(f, "w") as f:
            f.write(line)
    else:
        for ind, line in enumerate(fileinput.input(f, inplace=True)):
            if ind == rnd_n:
                print("{}\n".format(line) + line, end="")
            else:
                print(line, end="")

http://linux.die.net/man/3/fopen

a+ 打開以進行讀取和附加(在文件末尾寫入)。 如果文件不存在,則創建該文件。 讀取的初始文件位置在文件的開頭,但輸出始終附加到文件的末尾。

fileinput 制作您傳入的文件的f.bak副本,並在輸出關閉時將其刪除。 如果您指定備份擴展名backup=."foo" ,則將保留備份文件。

暫無
暫無

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

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