Hướng dẫn create temp directory python - tạo thư mục tạm thời python

Có một mô -đun tempfile cho Python, nhưng việc tạo tệp đơn giản cũng thực hiện thủ thuật:

new_file = open("path/to/FILE_NAME.ext", "w")

Bây giờ bạn có thể ghi vào nó bằng phương pháp write:

new_file.write('this is some content')

Với mô -đun tempfile, điều này có thể trông như thế này:

import tempfile

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)

Với mkstemp, bạn có trách nhiệm xóa tệp sau khi bạn hoàn thành nó. Với các đối số khác, bạn có thể ảnh hưởng đến thư mục và tên của tệp.


CẬP NHẬT

Như được chỉ ra một cách chính đáng bởi Emmet Speer, có những cân nhắc về bảo mật khi sử dụng mkstemp, vì mã máy khách chịu trách nhiệm đóng/làm sạch tệp đã tạo. Một cách tốt hơn để xử lý nó là đoạn trích sau (như lấy từ liên kết):

import os
import tempfile

fd, path = tempfile.mkstemp()
try:
    with os.fdopen(fd, 'w') as tmp:
        # do stuff with temp file
        tmp.write('stuff')
finally:
    os.remove(path)

new_file.write('this is some content')
1 kết thúc bộ mô tả tệp trong đối tượng tệp Python, tự động đóng khi
new_file.write('this is some content')
2 thoát. Cuộc gọi đến
new_file.write('this is some content')
3 xóa tệp khi không còn cần thiết.

Thay thế từ phiên bản 2.3: sử dụng

new_file.write('this is some content')
8 thay thế. Lib/tempfile.py


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à đối số DIR tương tự như của

new_file.write('this is some content')
8, ngoại trừ tên tệp byte,
new_file.write('this is some content')
36 và
new_file.write('this is some content')
37 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.

new_file.write('this is some content')
29 sử dụng có thể được thay thế dễ dàng bằng
new_file.write('this is some content')
39, chuyển cho nó tham số
new_file.write('this is some content')
40:

Mã nguồn: lib/tempfile.py(mode='w+b', buffering=- 1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)

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ợ.

new_file.write('this is some content')
4,
new_file.write('this is some content')
5,
new_file.write('this is some content')
6 và
new_file.write('this is some content')
7 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ý ngữ cảnh.
new_file.write('this is some content')
8 và
new_file.write('this is some content')
9 là các chức năng cấp thấp hơn yêu cầu dọn dẹp thủ công.file-like object that can be used as a temporary storage area. The file is created securely, using the same rules as
new_file.write('this is some content')
8. 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

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)
3 để 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

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)
4.

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

new_file.write('this is some content')
8.

Đố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

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)
6 là đối tượng tệp thực cơ bản.

Cờ

import tempfile

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)
7 được sử dụng nếu nó có sẵn và hoạt động (cụ thể 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

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)
8 với đối số
import tempfile

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)
9.auditing event
import tempfile

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)
8 with argument
import tempfile

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)
9.

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

import tempfile

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)
7 hiện được sử dụng nếu có.The
import tempfile

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)
7 flag is now used if available.

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

________ 20 ________ 32 (mode = 'w+b', buffering =- 1, mã hóa = none, newline = none(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 os
import tempfile

fd, path = tempfile.mkstemp()
try:
    with os.fdopen(fd, 'w') as tmp:
        # do stuff with temp file
        tmp.write('stuff')
finally:
    os.remove(path)
3, 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 os
import tempfile

fd, path = tempfile.mkstemp()
try:
    with os.fdopen(fd, 'w') as tmp:
        # do stuff with temp file
        tmp.write('stuff')
finally:
    os.remove(path)
4 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

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)
6 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
import os
import tempfile

fd, path = tempfile.mkstemp()
try:
    with os.fdopen(fd, 'w') as tmp:
        # do stuff with temp file
        tmp.write('stuff')
finally:
    os.remove(path)
6, giống như một tệp thông thường.

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

import tempfile

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)
8 với đối số
import tempfile

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)
9.auditing event
import tempfile

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)
8 with argument
import tempfile

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)
9.

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

________ 20 ________ 32 (mode = 'w+b', buffering =- 1, mã hóa = none, newline = none(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 os
import tempfile

fd, path = tempfile.mkstemp()
try:
    with os.fdopen(fd, 'w') as tmp:
        # do stuff with temp file
        tmp.write('stuff')
finally:
    os.remove(path)
3, 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 os
import tempfile

fd, path = tempfile.mkstemp()
try:
    with os.fdopen(fd, 'w') as tmp:
        # do stuff with temp file
        tmp.write('stuff')
finally:
    os.remove(path)
4 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

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)
6 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
import os
import tempfile

fd, path = tempfile.mkstemp()
try:
    with os.fdopen(fd, 'w') as tmp:
        # do stuff with temp file
        tmp.write('stuff')
finally:
    os.remove(path)
6, giống như một tệp thông thường.

Lớp ________ 20 ________ 40 (max_size = 0, mode = 'w+b', buffering =- 1, mã hóa = không

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

import os
import tempfile

fd, path = tempfile.mkstemp()
try:
    with os.fdopen(fd, 'w') as tmp:
        # do stuff with temp file
        tmp.write('stuff')
finally:
    os.remove(path)
3, 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 ____ ____42 đượ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 os
import tempfile

fd, path = tempfile.mkstemp()
try:
    with os.fdopen(fd, 'w') as tmp:
        # do stuff with temp file
        tmp.write('stuff')
finally:
    os.remove(path)
3.

Tệp kết quả có một phương thức bổ sung,

>>> 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, khiến cho tệp cuộn qua một tệp trên đĩa bất kể kích thước của nó.the truncate method now accepts a
>>> 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
0 argument.

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

________ 20 ________ 32 (mode = 'w+b', buffering =- 1, mã hóa = none, newline = none(suffix=None, prefix=None, dir=None, ignore_cleanup_errors=False)

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

import os
import tempfile

fd, path = tempfile.mkstemp()
try:
    with os.fdopen(fd, 'w') as tmp:
        # do stuff with temp file
        tmp.write('stuff')
finally:
    os.remove(path)
3, 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 os
import tempfile

fd, path = tempfile.mkstemp()
try:
    with os.fdopen(fd, 'w') as tmp:
        # do stuff with temp file
        tmp.write('stuff')
finally:
    os.remove(path)
4 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

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)
6 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
import os
import tempfile

fd, path = tempfile.mkstemp()
try:
    with os.fdopen(fd, 'w') as tmp:
        # do stuff with temp file
        tmp.write('stuff')
finally:
    os.remove(path)
6, giống như một tệp thông thường.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.

Lớp ________ 20 ________ 40 (max_size = 0, mode = 'w+b', buffering =- 1, mã hóa = không

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

import os
import tempfile

fd, path = tempfile.mkstemp()
try:
    with os.fdopen(fd, 'w') as tmp:
        # do stuff with temp file
        tmp.write('stuff')
finally:
    os.remove(path)
3, 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 ____ ____42 đượ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 os
import tempfile

fd, path = tempfile.mkstemp()
try:
    with os.fdopen(fd, 'w') as tmp:
        # do stuff with temp file
        tmp.write('stuff')
finally:
    os.remove(path)
3.

Tệp kết quả có một phương thức bổ sung,

>>> 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, khiến cho tệp cuộn qua một tệp trên đĩa bất kể kích thước của nó.auditing event tempfile1 with argument
import tempfile

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)
9.

Đối tượng được trả về 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
5 là đối tượ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
6 hoặ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
7 (tùy thuộc vào chế độ nhị phân hay văn bản được chỉ định) hoặc đối tượng tệp thực, tùy thuộc vào việ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 gọi. Đối tượng giống như tệp này có thể được sử dụng trong câu lệnh
import os
import tempfile

fd, path = tempfile.mkstemp()
try:
    with os.fdopen(fd, 'w') as tmp:
        # do stuff with temp file
        tmp.write('stuff')
finally:
    os.remove(path)
6, giống như một tệp thông thường.

Đã thay đổi trong phiên bản 3.3: Phương thức cắt ngắn hiện chấp nhận đối số

>>> 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
0.Added ignore_cleanup_errors parameter.

Lớp ________ 20 ________ 52 (hậu tố = không, tiền tố = none, dir = none, ond_cleanup_errors = false)(suffix=None, prefix=None, dir=None, text=False)

Lớp này tạo ra một thư mục tạm thời bằng cách sử dụng các quy tắc tương tự như

new_file.write('this is some content')
9. Đố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 thư mục tạm thời, thư mục tạm thời mới được tạo và tất cả các nội dung của nó được xóa khỏi hệ thống tập tin.

Không giống như

import os
import tempfile

fd, path = tempfile.mkstemp()
try:
    with os.fdopen(fd, 'w') as tmp:
        # do stuff with temp file
        tmp.write('stuff')
finally:
    os.remove(path)
3, người dùng của
new_file.write('this is some content')
8 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à tempfile9, 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ố.

new_file.write('this is some content')
8 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à tempfile9, 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 write2 hoặc write3, nếu phù hợp.

Nếu dir không phải là tempfile9, 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 write5.

Nếu bất kỳ hậu tố, tiền tố và dir không phải là tempfile9, chúng phải là cùng 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 write7.

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.

new_file.write('this is some content')
8 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 tempfile6) 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

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)
8 với đối số
import tempfile

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)
9.auditing event
import tempfile

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)
8 with argument
import tempfile

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)
9.

Đã 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à tempfile9 để 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 tempfile9 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.

________ 20 ________ 84 (hậu tố = không, tiền tố = none, dir = none) ¶(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

new_file.write('this is some content')
9 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

new_file.write('this is some content')
8.

new_file.write('this is some content')
9 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 tempfile1 với đối số

import tempfile

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)
9.auditing event tempfile1 with argument
import tempfile

new_file, filename = tempfile.mkstemp()

print(filename)

os.write(new_file, "this is some content")
os.close(new_file)
9.

Đã 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à tempfile9 để 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 tempfile9 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.

________ 20 ________ 84 (hậu tố = không, tiền tố = 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

new_file.write('this is some content')
9 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

    new_file.write('this is some content')
    
    8.mkstemp3 environment variable.

  2. new_file.write('this is some content')
    
    9 Trả về tên đường dẫn tuyệt đối của thư mục mới.mkstemp4 environment variable.

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

    import tempfile
    
    new_file, filename = tempfile.mkstemp()
    
    print(filename)
    
    os.write(new_file, "this is some content")
    os.close(new_file)
    
    9.mkstemp5 environment variable.

  4. ________ 20 ________ 92 ()

    • 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à:

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

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

Thư mục được đặt tên bởi biến môi trường mkstemp5.Always returns a str. Previously it would return any

new_file.write('this is some content')
03 value regardless of type so long as it was not tempfile9.

Vị trí cụ thể của nền tảng:()

Trên Windows, các thư mục mkstemp6, mkstemp7, mkstemp8 và mkstemp9, theo thứ tự đó.

Trên tất cả các nền tảng khác, các thư mục

new_file.write('this is some content')
00,
new_file.write('this is some content')
01 và
new_file.write('this is some content')
02, 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

new_file.write('this is some content')
03 bên dưới.

Đã 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ị
new_file.write('this is some content')
03 nào bất kể loại nào miễn là nó không phải là tempfile9.()

________ 20 ________ 107 ()

Trên tất cả các nền tảng khác, các thư mục

new_file.write('this is some content')
00,
new_file.write('this is some content')
01 và
new_file.write('this is some content')
02, 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
new_file.write('this is some content')
03 bên dưới.

Khi được đặt thành một giá trị khác với tempfile9, 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

new_file.write('this is some content')
03 là tempfile9 (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ừ write2, nó sẽ được khởi tạo theo thuật toán được mô tả trong
new_file.write('this is some content')
08.

Ghi chú

Hãy coi chừng nếu bạn đặt

new_file.write('this is some content')
03 thành giá trị byte, có một tác dụng phụ khó chịu: loại trả về mặc định toàn cầu là
new_file.write('this is some content')
8 và
new_file.write('this is some content')
9 thay đổi thành byte khi không có đối số
new_file.write('this is some content')
25,
new_file.write('this is some content')
26 hoặc
new_file.write('this is some content')
27 của STR đượ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

new_file.write('this is some content')
28:

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

new_file.write('this is some content')
29 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
new_file.write('this is some content')
29 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
new_file.write('this is some content')
8 và các chức năng khác được mô tả ở trên.

________ 20 ________ 133 (hậu tố = '', tiền tố = 'tmp', dir = none) ¶(suffix='', prefix='tmp', dir=None)

Thay thế từ phiên bản 2.3: sử dụng

new_file.write('this is some content')
8 thay thế.Use
new_file.write('this is some content')
8 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à đối số DIR tương tự như của

new_file.write('this is some content')
8, ngoại trừ tên tệp byte,
new_file.write('this is some content')
36 và
new_file.write('this is some content')
37 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.

new_file.write('this is some content')
29 sử dụng có thể được thay thế dễ dàng bằng
new_file.write('this is some content')
39, chuyển cho nó tham số
new_file.write('this is some content')
40:

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