Hướng dẫn what is used to store temporary data in python? - những gì được sử dụng để lưu trữ dữ liệu tạm thời trong python?

Tôi đồng ý với nhận xét của Zvone. Để biết giải pháp tốt nhất, chúng tôi sẽ cần thêm thông tin.

Sau đây sẽ là một giải pháp mạnh mẽ và có thể định cấu hình.

import os
import pickle


backup_interval = 2
backup_file = 'gps_position_backup.bin'


def read_backup_data():
    file_backup_data = []
    if os.path.exists(backup_file):
        with open(backup_file, 'rb') as f:
            while True:
                try:
                    coordinates = pickle.load(f)
                except EOFError:
                    break
                file_backup_data += coordinates

    return file_backup_data


# When the script is started and backup data exists, stageddata uses it
stageddata = read_backup_data()


def write_backup_data():
    tmp_backup_file = 'tmp_' + backup_file
    with open(tmp_backup_file, 'wb') as f:
        pickle.dump(stageddata, f)
    os.replace(tmp_backup_file, backup_file)
    print('Wrote data backup!')


# Mockup variable and method
transmission_return = False
def transmission(position):
    return transmission_return


def try_transmission(position):
    if not transmission(position):
        stageddata.append(position)
        if len(stageddata) % backup_interval == 0:
            write_backup_data()
    else:
        while stageddata:
            position = stageddata.pop()
            if not transmission(position):
                stageddata.append(position)
                return
            else:
                if len(stageddata) % backup_interval == 0:
                    write_backup_data()


if __name__ == '__main__':
    # transmission_return is False, so write to backup_file
    for counter in range(10):
        position = {'lat':'1.2345', 'lon':'2.3455'}
        try_transmission(position)

    # transmission_return is True, transmit positions and "update" backup_file
    transmission_return = True
    position = {'lat':'1.2345', 'lon':'2.3455'}
    try_transmission(position)

Tôi đã chuyển mã của bạn vào một số chức năng. Với biến Backup_interval biến, có thể kiểm soát tần suất sao lưu được ghi vào đĩa.

Ghi chú bổ sung:

  • Tôi sử dụng mô-đun Pickle tích hợp, vì dữ liệu không phải là người có thể đọc được hoặc có thể chuyển đổi cho các ngôn ngữ lập trình khác. Các lựa chọn thay thế là JSON, có thể đọc được con người, hoặc MSGPack, có thể nhanh hơn, nhưng cần một gói bổ sung để được cài đặt. Tempfile không phải là một giải pháp pythonic, vì nó không thể dễ dàng lấy được trong trường hợp chương trình gặp sự cố.
  • StagedData được viết vào đĩa khi nó nhấn vào Backup_Interval (rõ ràng), nhưng cũng khi truyền trả về đúng trong vòng lặp. Điều này là cần thiết để "đồng bộ hóa" dữ liệu trên đĩa.
  • Dữ liệu được ghi vào đĩa hoàn toàn mới mỗi lần. Một cách tiếp cận tinh vi hơn là chỉ nối các vị trí mới được thêm vào, nhưng sau đó phần đồng bộ hóa, mà tôi đã mô tả trước đây, cũng sẽ phức tạp hơn. Ngoài ra, cách tiếp cận tệp tạm thời an toàn hơn (xem chỉnh sửa bên dưới) sẽ không hoạt động.

EDIT: Tôi vừa xem xét lại trường hợp sử dụng của bạn. Vấn đề chính ở đây là: Khôi phục dữ liệu, ngay cả khi chương trình bị gián đoạn bất cứ lúc nào (do gián đoạn điện hoặc bất cứ điều gì). Giải pháp đầu tiên của tôi chỉ viết dữ liệu cho đĩa (giải quyết một phần của vấn đề), nhưng nó vẫn có thể xảy ra, chương trình này đã gặp sự cố khi viết vào đĩa. Trong trường hợp đó, tệp có thể sẽ bị hỏng và dữ liệu bị mất. Tôi đã điều chỉnh hàm write_backup_data (), để nó ghi vào một tệp tạm thời trước và sau đó thay thế tệp cũ. Vì vậy, bây giờ, ngay cả khi rất nhiều dữ liệu phải được ghi vào đĩa và sự cố xảy ra ở đó, tệp sao lưu trước đó vẫn sẽ có sẵn.: I just reconsidered your use case. The main problem here is: Restoring data, even if the program gets interrupted at any time (due to power interruption or whatever). My first solution just wrote the data to disk (which solves part of the problem), but it could still happen, that the program crashes the moment when writing to disk. In that case the file would probably be corrupt and the data lost. I adapted the function write_backup_data(), so that it writes to a temporary file first and then replaces the old file. So now, even if a lot of data has to be written to disk and the crash happens there, the previous backup file would still be available.

Mã nguồn: lib/tempfile.py Lib/tempfile.py


Mô -đun này tạo ra các tập tin và thư mục tạm thời. Nó hoạt động trên tất cả các nền tảng được hỗ trợ. TemporaryFile, NamedTemporaryFile, TemporaryDirectorySpooledTemporaryFile là các giao diện cấp cao cung cấp việc dọn dẹp tự động và có thể được sử dụng làm người quản lý bối cảnh. mkstemp()mkdtemp() là các chức năng cấp thấp hơn yêu cầu dọn dẹp thủ công.

Tất cả các chức năng và trình xây dựng có thể gọi người dùng đều có các đối số bổ sung cho phép kiểm soát trực tiếp vị trí và tên của các tệp và thư mục tạm thời. Tên các tệp được sử dụng bởi mô -đun này bao gồm một chuỗi các ký tự ngẫu nhiên cho phép các tệp đó được tạo an toàn trong các thư mục tạm thời được chia sẻ. Để duy trì khả năng tương thích ngược, thứ tự đối số có phần kỳ lạ; Nên sử dụng các đối số từ khóa để rõ ràng.

Mô-đun xác định các mục có thể gọi người dùng sau:

tempfile.temdyfile (mode = 'w+b', buffering = -1, mã hóa = không, newline = none, hậu tố = không, tiền tố = khôngTemporaryFile(mode='w+b', buffering=- 1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)

Trả về một đối tượng giống như tệp có thể được sử dụng làm khu vực lưu trữ tạm thời. Tệp được tạo an toàn, sử dụng các quy tắc tương tự như mkstemp(). Nó sẽ bị phá hủy ngay khi nó được đóng lại (bao gồm cả một đóng cửa ngầm khi đối tượng được thu thập rác). Trong Unix, mục nhập thư mục cho tệp hoàn toàn không được tạo hoặc bị xóa ngay sau khi tệp được tạo. Các nền tảng khác không hỗ trợ điều này; Mã của bạn không nên dựa vào một tệp tạm thời được tạo bằng cách sử dụng chức năng này hoặc không có tên hiển thị trong hệ thống tệp.file-like object that can be used as a temporary storage area. The file is created securely, using the same rules as mkstemp(). It will be destroyed as soon as it is closed (including an implicit close when the object is garbage collected). Under Unix, the directory entry for the file is either not created at all or is removed immediately after the file is created. Other platforms do not support this; your code should not rely on a temporary file created using this function having or not having a visible name in the file system.

Đối tượng kết quả có thể được sử dụng làm trình quản lý ngữ cảnh (xem ví dụ). Khi hoàn thành bối cảnh hoặc phá hủy đối tượng tệp, tệp tạm thời sẽ bị xóa khỏi hệ thống tập tin.Examples). On completion of the context or destruction of the file object the temporary file will be removed from the filesystem.

Tham số chế độ mặc định là

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
0 để tệp được tạo và ghi mà không bị đóng. Chế độ nhị phân được sử dụng để nó hoạt động liên tục trên tất cả các nền tảng mà không liên quan đến dữ liệu được lưu trữ. Bộ đệm, mã hóa, lỗi và dòng mới được hiểu là đối với
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
1.

Các tham số DIR, tiền tố và hậu tố có cùng ý nghĩa và mặc định như với mkstemp().

Đối tượng được trả về là một đối tượng tệp thực trên các nền tảng POSIX. Trên các nền tảng khác, nó là một đối tượng giống như tệp có thuộc tính

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
3 là đối tượng tệp thực tế.

Cờ

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
4 được sử dụng nếu nó có sẵn và hoạt động (đặc trưng của Linux, yêu cầu nhân Linux 3.11 trở lên).

Trên các nền tảng không phải là POSIX hay Cygwin, TemplayFile là bí danh của tên được đặt tên.

Tăng một sự kiện kiểm toán

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
5 với đối số
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
6.auditing event
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
5 with argument
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
6.

Đã thay đổi trong phiên bản 3.5: cờ

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
4 hiện được sử dụng nếu có.The
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
4 flag is now used if available.

Đã thay đổi trong phiên bản 3.8: Đã thêm tham số lỗi.Added errors parameter.

Tempfile.namedTeMdyFile (mode = 'w+b', buffering = -1, expoding = none, newline = noneNamedTemporaryFile(mode='w+b', buffering=- 1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True, *, errors=None)

Hàm này hoạt động chính xác như

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
8, ngoại trừ tệp được đảm bảo có tên hiển thị trong hệ thống tệp (trên Unix, mục nhập thư mục không được liên kết). Tên đó có thể được lấy từ thuộc tính
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
9 của đối tượng giống như tệp được trả về. Liệu tên có thể được sử dụng để mở tệp lần thứ hai hay không, trong khi tệp tạm thời được đặt tên vẫn còn mở, thay đổi giữa các nền tảng (nó có thể được sử dụng trên Unix; nó không thể trên Windows). Nếu xóa là đúng (mặc định), tệp sẽ bị xóa ngay khi đóng. Đối tượng được trả về luôn là một đối tượng giống như tệp có thuộc tính
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
3 là đối tượng tệp thực cơ bản. Đối tượng giống như tệp này có thể được sử dụng trong câu lệnh
>>> f = NamedTemporaryFile(delete=False)
>>> f.name
'/tmp/tmptjujjt'
>>> f.write(b"Hello World!\n")
13
>>> f.close()
>>> os.unlink(f.name)
>>> os.path.exists(f.name)
False
1, giống như một tệp thông thường.

Trên POSIX (chỉ), một quy trình bị chấm dứt đột ngột với Sigkill không thể tự động xóa bất kỳ tên gọi nào mà nó tạo ra.

Tăng một sự kiện kiểm toán

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
5 với đối số
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
6.auditing event
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
5 with argument
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
6.

Đã thay đổi trong phiên bản 3.8: Đã thêm tham số lỗi.Added errors parameter.

Tempfile.namedTeMdyFile (mode = 'w+b', buffering = -1, expoding = none, newline = none tempfile.SpooledTemporaryFile(max_size=0, mode='w+b', buffering=- 1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)

Hàm này hoạt động chính xác như

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
8, ngoại trừ tệp được đảm bảo có tên hiển thị trong hệ thống tệp (trên Unix, mục nhập thư mục không được liên kết). Tên đó có thể được lấy từ thuộc tính
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
9 của đối tượng giống như tệp được trả về. Liệu tên có thể được sử dụng để mở tệp lần thứ hai hay không, trong khi tệp tạm thời được đặt tên vẫn còn mở, thay đổi giữa các nền tảng (nó có thể được sử dụng trên Unix; nó không thể trên Windows). Nếu xóa là đúng (mặc định), tệp sẽ bị xóa ngay khi đóng. Đối tượng được trả về luôn là một đối tượng giống như tệp có thuộc tính
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
3 là đối tượng tệp thực cơ bản. Đối tượng giống như tệp này có thể được sử dụng trong câu lệnh
>>> f = NamedTemporaryFile(delete=False)
>>> f.name
'/tmp/tmptjujjt'
>>> f.write(b"Hello World!\n")
13
>>> f.close()
>>> os.unlink(f.name)
>>> os.path.exists(f.name)
False
1, giống như một tệp thông thường.

Trên POSIX (chỉ), một quy trình bị chấm dứt đột ngột với Sigkill không thể tự động xóa bất kỳ tên gọi nào mà nó tạo ra.

classtempfile.spooledtemdyfile (max_size = 0, mode = 'w+b', buffering = -1, expoding = none, newline = none, hậu tố = không, tiền tố = không, dir = none,

Lớp này hoạt động chính xác như

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
8, ngoại trừ dữ liệu được trình bày trong bộ nhớ cho đến khi kích thước tệp vượt quá MAX_SIZE hoặc cho đến khi phương thức tệp ____ ____25 được gọi, tại thời điểm đó, nội dung được ghi vào đĩa và hoạt động tiến hành như với
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
8.the truncate method now accepts a TemporaryFile3 argument.

Đã thay đổi trong phiên bản 3.8: Đã thêm tham số lỗi.Added errors parameter.

Tempfile.namedTeMdyFile (mode = 'w+b', buffering = -1, expoding = none, newline = noneFully implements the TemporaryFile4 and TemporaryFile5 abstract base classes (depending on whether binary or text mode was specified).

Hàm này hoạt động chính xác như
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
8, ngoại trừ tệp được đảm bảo có tên hiển thị trong hệ thống tệp (trên Unix, mục nhập thư mục không được liên kết). Tên đó có thể được lấy từ thuộc tính
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
9 của đối tượng giống như tệp được trả về. Liệu tên có thể được sử dụng để mở tệp lần thứ hai hay không, trong khi tệp tạm thời được đặt tên vẫn còn mở, thay đổi giữa các nền tảng (nó có thể được sử dụng trên Unix; nó không thể trên Windows). Nếu xóa là đúng (mặc định), tệp sẽ bị xóa ngay khi đóng. Đối tượng được trả về luôn là một đối tượng giống như tệp có thuộc tính
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
3 là đối tượng tệp thực cơ bản. Đối tượng giống như tệp này có thể được sử dụng trong câu lệnh
>>> f = NamedTemporaryFile(delete=False)
>>> f.name
'/tmp/tmptjujjt'
>>> f.write(b"Hello World!\n")
13
>>> f.close()
>>> os.unlink(f.name)
>>> os.path.exists(f.name)
False
1, giống như một tệp thông thường.
tempfile.TemporaryDirectory(suffix=None, prefix=None, dir=None, ignore_cleanup_errors=False)

Trên POSIX (chỉ), một quy trình bị chấm dứt đột ngột với Sigkill không thể tự động xóa bất kỳ tên gọi nào mà nó tạo ra.Examples). On completion of the context or destruction of the temporary directory object, the newly created temporary directory and all its contents are removed from the filesystem.

classtempfile.spooledtemdyfile (max_size = 0, mode = 'w+b', buffering = -1, expoding = none, newline = none, hậu tố = không, tiền tố = không, dir = none,

Lớp này hoạt động chính xác như

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
8, ngoại trừ dữ liệu được trình bày trong bộ nhớ cho đến khi kích thước tệp vượt quá MAX_SIZE hoặc cho đến khi phương thức tệp ____ ____25 được gọi, tại thời điểm đó, nội dung được ghi vào đĩa và hoạt động tiến hành như với
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
8.

Tăng một sự kiện kiểm toán NamedTemporaryFile4 với đối số

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
6.auditing event NamedTemporaryFile4 with argument
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
6.

Mới trong phiên bản 3.2.

Đã thay đổi trong phiên bản 3.10: Đã thêm tham số bỏ qua_cleanup_errors.Added ignore_cleanup_errors parameter.

tempfile.mkstemp (hậu tố = không, tiền tố = none, dir = none, text = false) ¶mkstemp(suffix=None, prefix=None, dir=None, text=False)

Tạo một tập tin tạm thời theo cách an toàn nhất có thể. Không có điều kiện đua trong việc tạo tệp, giả sử rằng nền tảng thực hiện đúng cờ NamedTemporaryFile6 cho NamedTemporaryFile7. Tệp có thể đọc được và chỉ có thể ghi bằng ID người dùng tạo. Nếu nền tảng sử dụng các bit quyền để cho biết liệu một tệp có thể thực thi được hay không, thì tệp không thể thực thi được bởi không ai. Bộ mô tả tập tin không được kế thừa bởi các quá trình con.

Không giống như

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
8, người dùng của mkstemp() chịu trách nhiệm xóa tệp tạm thời khi thực hiện với nó.

Nếu hậu tố không phải là TemporaryDirectory0, tên tệp sẽ kết thúc với hậu tố đó, nếu không sẽ không có hậu tố. mkstemp() không đặt dấu chấm giữa tên tệp và hậu tố; Nếu bạn cần một, hãy đặt nó ở đầu hậu tố.

Nếu tiền tố không phải là TemporaryDirectory0, tên tệp sẽ bắt đầu với tiền tố đó; Nếu không, một tiền tố mặc định được sử dụng. Mặc định là giá trị trả về của TemporaryDirectory3 hoặc TemporaryDirectory4, nếu phù hợp.

Nếu DIR không phải là TemporaryDirectory0, tệp sẽ được tạo trong thư mục đó; Nếu không, một thư mục mặc định được sử dụng. Thư mục mặc định được chọn từ danh sách phụ thuộc vào nền tảng, nhưng người dùng ứng dụng có thể kiểm soát vị trí thư mục bằng cách đặt các biến môi trường TMPDIR, TEMP hoặc TMP. Do đó, không có gì đảm bảo rằng tên tệp được tạo sẽ có bất kỳ thuộc tính đẹp nào, chẳng hạn như không yêu cầu trích dẫn khi được chuyển cho các lệnh bên ngoài thông qua TemporaryDirectory6.

Nếu bất kỳ hậu tố, tiền tố và dir không phải là TemporaryDirectory0, chúng phải là cùng một loại. Nếu chúng là byte, tên trả về sẽ là byte thay vì str. Nếu bạn muốn buộc một byte trả về giá trị với hành vi mặc định khác, hãy vượt qua TemporaryDirectory8.

Nếu văn bản được chỉ định và đúng, tệp được mở ở chế độ văn bản. Mặt khác, (mặc định) tệp được mở ở chế độ nhị phân.

mkstemp() Trả về một tuple chứa một tay cầm cấp hệ điều hành cho một tệp mở (như sẽ được trả về bởi NamedTemporaryFile7) và tên đường dẫn tuyệt đối của tệp đó, theo thứ tự đó.

Tăng một sự kiện kiểm toán

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
5 với đối số
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
6.auditing event
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
5 with argument
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
6.

Đã thay đổi trong phiên bản 3.5: Hậu tố, tiền tố và dir hiện có thể được cung cấp theo byte để có được giá trị trả về byte. Trước đó, chỉ có STR được phép. Hậu tố và tiền tố hiện chấp nhận và mặc định là TemporaryDirectory0 để gây ra giá trị mặc định phù hợp được sử dụng.suffix, prefix, and dir may now be supplied in bytes in order to obtain a bytes return value. Prior to this, only str was allowed. suffix and prefix now accept and default to TemporaryDirectory0 to cause an appropriate default value to be used.

Đã thay đổi trong phiên bản 3.6: Tham số Dir hiện chấp nhận một đối tượng giống như đường dẫn.The dir parameter now accepts a path-like object.

tempfile.mkdtemp (hậu tố = không, tiền tố = không, dir = none) ¶mkdtemp(suffix=None, prefix=None, dir=None)

Tạo một thư mục tạm thời theo cách an toàn nhất có thể. Không có điều kiện chủng tộc trong việc tạo thư mục. Thư mục có thể đọc được, có thể ghi và chỉ có thể tìm kiếm bằng ID người dùng tạo.

Người dùng của mkdtemp() chịu trách nhiệm xóa thư mục tạm thời và nội dung của nó khi thực hiện với nó.

Tiền tố, hậu tố và đối số DIR giống như đối với mkstemp().

mkdtemp() Trả về tên đường dẫn tuyệt đối của thư mục mới.

Tăng một sự kiện kiểm toán NamedTemporaryFile4 với đối số

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
6.auditing event NamedTemporaryFile4 with argument
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
6.

Đã thay đổi trong phiên bản 3.5: Hậu tố, tiền tố và dir hiện có thể được cung cấp theo byte để có được giá trị trả về byte. Trước đó, chỉ có STR được phép. Hậu tố và tiền tố hiện chấp nhận và mặc định là TemporaryDirectory0 để gây ra giá trị mặc định phù hợp được sử dụng.suffix, prefix, and dir may now be supplied in bytes in order to obtain a bytes return value. Prior to this, only str was allowed. suffix and prefix now accept and default to TemporaryDirectory0 to cause an appropriate default value to be used.

Đã thay đổi trong phiên bản 3.6: Tham số Dir hiện chấp nhận một đối tượng giống như đường dẫn.The dir parameter now accepts a path-like object.

tempfile.mkdtemp (hậu tố = không, tiền tố = không, dir = none) ¶gettempdir()

Tạo một thư mục tạm thời theo cách an toàn nhất có thể. Không có điều kiện chủng tộc trong việc tạo thư mục. Thư mục có thể đọc được, có thể ghi và chỉ có thể tìm kiếm bằng ID người dùng tạo.

Người dùng của mkdtemp() chịu trách nhiệm xóa thư mục tạm thời và nội dung của nó khi thực hiện với nó.

  1. Tiền tố, hậu tố và đối số DIR giống như đối với mkstemp().mkstemp()0 environment variable.

  2. mkdtemp() Trả về tên đường dẫn tuyệt đối của thư mục mới.mkstemp()1 environment variable.

  3. tempfile.gettempdir () ¶mkstemp()2 environment variable.

  4. Trả về tên của thư mục được sử dụng cho các tệp tạm thời. Điều này xác định giá trị mặc định cho đối số DIR cho tất cả các hàm trong mô -đun này.

    • Python tìm kiếm một danh sách tiêu chuẩn các thư mục để tìm một danh sách mà người dùng gọi có thể tạo tệp. Danh sách là:

    • Thư mục được đặt tên bởi biến môi trường mkstemp()0.

  5. Thư mục được đặt tên bởi biến môi trường mkstemp()1.

Thư mục được đặt tên bởi biến môi trường mkstemp()2.

Vị trí cụ thể của nền tảng:Always returns a str. Previously it would return any mkdtemp()0 value regardless of type so long as it was not TemporaryDirectory0.

Trên Windows, các thư mục mkstemp()3, mkstemp()4, mkstemp()5 và mkstemp()6, theo thứ tự đó.gettempdirb()

Trên tất cả các nền tảng khác, các thư mục mkstemp()7, mkstemp()8 và mkstemp()9, theo thứ tự đó.

Là một phương sách cuối cùng, thư mục làm việc hiện tại.

Kết quả của tìm kiếm này được lưu trữ, xem mô tả của mkdtemp()0 bên dưới.gettempprefix()

Đã thay đổi trong phiên bản 3.10: Luôn trả về STR. Trước đây, nó sẽ trả về bất kỳ giá trị mkdtemp()0 nào bất kể loại nào miễn là nó không phải là TemporaryDirectory0.

tempfile.gettempprefixb () ¶gettempprefixb()

Giống như TemporaryDirectory3 nhưng giá trị trả về là trong byte.

Mới trong phiên bản 3.5.

Mô -đun sử dụng biến toàn cầu để lưu trữ tên của thư mục được sử dụng cho các tệp tạm thời được trả về bởi mkdtemp()3. Nó có thể được đặt trực tiếp để ghi đè quá trình lựa chọn, nhưng điều này không được khuyến khích. Tất cả các chức năng trong mô -đun này có một đối số DIR có thể được sử dụng để chỉ định thư mục. Đây là cách tiếp cận được đề xuất không gây ngạc nhiên cho mã không nghi ngờ khác bằng cách thay đổi hành vi API toàn cầu.

tempfile.tempdir¶tempdir

Khi được đặt thành một giá trị khác với TemporaryDirectory0, biến này xác định giá trị mặc định cho đối số DIR cho các hàm được xác định trong mô -đun này, bao gồm loại, byte hoặc str. Nó không thể là một đối tượng giống như đường dẫn.path-like object.

Nếu mkdtemp()0 là TemporaryDirectory0 (mặc định) tại bất kỳ cuộc gọi nào đến bất kỳ chức năng nào ở trên ngoại trừ TemporaryDirectory3, nó sẽ được khởi tạo theo thuật toán được mô tả trong mkdtemp()3.

Ghi chú

Hãy coi chừng nếu bạn đặt mkdtemp()0 thành giá trị byte, thì có một tác dụng phụ khó chịu: loại trả về mặc định toàn cầu là mkstemp()mkdtemp() thay đổi thành byte khi không có đối số mkstemp()4, mkstemp()5 hoặc mkstemp()6 được cung cấp. Vui lòng không viết mã mong đợi hoặc tùy thuộc vào điều này. Hành vi khó xử này được duy trì để tương thích với việc thực hiện lịch sử.

Ví dụ;

Dưới đây là một số ví dụ về cách sử dụng điển hình của mô -đun mkstemp()7:

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed

Chức năng và biến không dùng nữa

Một cách lịch sử để tạo các tệp tạm thời là trước tiên tạo tên tệp với hàm mkstemp()8 và sau đó tạo một tệp bằng tên này. Thật không may, điều này không an toàn, bởi vì một quy trình khác có thể tạo một tệp có tên này trong thời gian giữa cuộc gọi đến mkstemp()8 và nỗ lực tiếp theo để tạo tệp theo quy trình đầu tiên. Giải pháp là kết hợp hai bước và tạo tệp ngay lập tức. Cách tiếp cận này được sử dụng bởi mkstemp() và các chức năng khác được mô tả ở trên.

tempfile.mktemp (hậu tố = '', tiền tố = 'tmp', dir = none) ¶mktemp(suffix='', prefix='tmp', dir=None)

Không dùng nữa kể từ phiên bản 2.3: sử dụng mkstemp() thay thế.Use mkstemp() instead.

Trả về một tên đường dẫn tuyệt đối của một tệp không tồn tại tại thời điểm cuộc gọi được thực hiện. Tiền tố, hậu tố và các đối số DIR tương tự như của mkstemp(), ngoại trừ tên tệp byte,

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
03 và
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
04 không được hỗ trợ.

Cảnh báo

Việc sử dụng chức năng này có thể giới thiệu một lỗ hổng bảo mật trong chương trình của bạn. Vào thời điểm bạn có thể làm bất cứ điều gì với tên tệp mà nó trả về, người khác có thể đã đánh bại bạn với cú đấm. mkstemp()8 sử dụng có thể được thay thế dễ dàng bằng

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
06, chuyển cho nó tham số ____107:

>>> f = NamedTemporaryFile(delete=False)
>>> f.name
'/tmp/tmptjujjt'
>>> f.write(b"Hello World!\n")
13
>>> f.close()
>>> os.unlink(f.name)
>>> os.path.exists(f.name)
False

Làm thế nào để Python lưu trữ dữ liệu tạm thời?

Để đạt được điều này, chúng ta có thể sử dụng hàm tạm thời () ...
Đầu tiên, chúng ta phải nhập tempfile sau đó tệp được tạo bằng hàm tạm thờifile () ..
Tệp được mở trong chế độ W+B (cả đọc và ghi vào tệp mở) theo mặc định ..
Hàm này tạo một tệp tạm thời trong thư mục tạm thời và trả về một đối tượng tệp ..

Python lưu trữ các tệp tạm thời ở đâu?

Hàm này trả về tên của thư mục để lưu trữ các tệp tạm thời.Tên này thường được lấy từ biến môi trường tempdir.Trên nền tảng Windows, thông thường là người dùng/appdata/local/temp hoặc windowsdir/temp hoặc systemdrive/temp.Trên Linux, nó thường là /TMP.user/AppData/Local/Temp or windowsdir/temp or systemdrive/temp. On linux it normally is /tmp.

Những gì được sử dụng để lưu trữ dữ liệu trong Python?

Sử dụng đối tượng tệp tích hợp của Python, có thể ghi dữ liệu chuỗi vào tệp đĩa và đọc từ nó.Thư viện tiêu chuẩn của Python, cung cấp các mô -đun để lưu trữ và truy xuất dữ liệu được tuần tự hóa trong các cấu trúc dữ liệu khác nhau như JSON và XML.DB-API của Python cung cấp một cách tương tác tiêu chuẩn với cơ sở dữ liệu quan hệ.Python's standard library, provides modules to store and retrieve serialized data in various data structures such as JSON and XML. Python's DB-API provides a standard way of interacting with relational databases.

Thư mục tạm thời Python là gì?

Tạm thờifile, được đặt tênTemdyfile, tạm thời và tạm thời là giao diện cấp cao cung cấp việc dọn dẹp tự động và có thể được sử dụng làm người quản lý bối cảnh.mkstemp () và mkdtemp () là các hàm cấp thấp hơn yêu cầu dọn dẹp thủ công.high-level interfaces which provide automatic cleanup and can be used as context managers. mkstemp() and mkdtemp() are lower-level functions which require manual cleanup.