Hướng dẫn rename temporary file python - đổi tên tập tin tạm thời python

Bạn cần vượt qua

def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
1 trong quá trình khởi tạo, cài đặt
def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
2 sau không hoạt động. Tôi đã có thể đổi tên nó sau khi viết với mã này:

with tempfile.NamedTemporaryFile[dir=os.getcwd[], delete=False] as f:
    f.write[b'foobar']
    f.flush[]
    os.rename[f.name, 'foobar']

Tôi đã trải qua mã của lib/tempfile.py để xác nhận hành vi này.

Khi bạn gọi

def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
3, nó sẽ khởi tạo và trả về một thể hiện của lớp
def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
4 được xác định trong cùng một tệp. Nhìn vào
def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
5 của lớp này:

def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]

Và đây là

def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
5 của lớp
def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
7:

def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete

Khi bạn thoát khỏi câu lệnh với câu lệnh, trong khi đóng tệp, thuộc tính

def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
8 của
def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
7 được kiểm tra. Trong khi khi bạn thực hiện
def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
2, bạn sẽ thay đổi thuộc tính
def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
8 của lớp
def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
4 thay vì lớp
def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
7. Do đó, hành vi đóng cửa không bị thay đổi ngay cả khi nó trông như thế ở phía nhà phát triển. Vì vậy, bạn phải vượt qua
def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
1 trong quá trình khởi tạo trong câu lệnh
def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
5 như trong ví dụ mã của tôi.

Nếu bạn vẫn muốn sửa đổi hành vi, bạn có thể truy cập thuộc tính

def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
6, tuy nhiên nó sẽ hơi xấu.

with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']

BTW, tôi đã thực hiện điều này trên Ubuntu WSL trên Windows 10. Tôi không chắc bạn đang sử dụng hệ điều hành nào, điều đó có thể ảnh hưởng đến hành vi.

Cách tạo một tệp/thư mục tạm thời với tên do người dùng xác định trong Python. Tôi biết về Tempfile. Tuy nhiên tôi không thể thấy bất kỳ chức năng nào với tên tệp là đối số.

Nội phân Chính showShow

  • Chức năng và biến không dùng nữa
  • Làm cách nào để tạo tệp TMP trong Python?
  • Làm cách nào để tạo một tệp CSV tạm thời trong Python?
  • Tempfile có tên làTemdyfile [] là gì?
  • Làm cách nào để tạo tệp TMP?

Để chèn một tên tệp tạm thời mới:.

Trong một hành động ghi vào tệp trong một bước, nhấp chuột phải vào trường tệp ..

Nhấp vào Tên tệp> Tên tệp mới. Cửa sổ thuộc tính FileName Mở ..25 gold badges160 silver badges284 bronze badges

Xác định các thuộc tính cho tệp tạm thời: Tên: Cung cấp tên cho tệp tạm thời [ví dụ: báo cáo]. ....Sep 20, 2016 at 11:09

5

Bấm OK ..

Cách tạo một tệp/thư mục tạm thời với tên do người dùng xác định trong Python. Tôi biết về Tempfile. Tuy nhiên tôi không thể thấy bất kỳ chức năng nào với tên tệp là đối số.

Nội phân Chính show

with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...

LƯU Ý: Tôi cần điều này để kiểm tra đơn vị chức năng GLOB [Tên tệp phù hợp] trên thư mục tạm thời chứa các tệp tạm thời thay vì sử dụng hệ thống tệp thực tế.

>>> import tempfile
>>> t = tempfile.TemporaryDirectory[]
>>> print[t]

>>> print[t.name]
/tmp/tmpqign52ry

MartineauMar 2 at 19:55

j314errej314errej314erre

Huy hiệu vàng 115K252 gold badges16 silver badges25 bronze badges

5

Bạn có thể sử dụng

def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
8 với bất kỳ tên tệp nào bạn cần.

e.g.

open[name, 'w']

Mở

Hoặc

import os
import tempfile

print 'Building a file name yourself:'
filename = '/tmp/guess_my_name.%s.txt' % os.getpid[]
temp = open[filename, 'w+b']
try:
    print 'temp:', temp
    print 'temp.name:', temp.name
finally:
    temp.close[]
    # Clean up the temporary file yourself
    os.remove[filename]

Hoặc bạn có thể tạo một thư mục tạm thời bằng cách sử dụng

def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
9 và sau đó sử dụng
with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']
0 để tạo một tệp trong thư mục tạm thời.

Đã trả lời ngày 20 tháng 9 năm 2016 lúc 11:19Sep 20, 2016 at 11:19

TechidiotechidiotTechidiot

1.9111 Huy hiệu vàng14 Huy hiệu bạc28 Huy hiệu đồng1 gold badge14 silver badges28 bronze badges

3

Tôi gần như thích viết theo cách phức tạp này bằng cách sử dụng

with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']
1, thay vì sử dụng
def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
8, bởi vì tôi thực sự muốn nhấn mạnh rằng đây là một tempfile:

import tempfile, os

with tempfile.NamedTemporaryFile[] as temp_fp:
    os.rename[temp_fp.name, '/tmp/my_custom_name.txt']
    # do stuff here ...

    # do stuff here END ...
    os.rename['/tmp/my_custom_name.txt', temp_fp.name] # finally, rename back
    

Chúng ta cần đổi tên lại vì: Cập nhật bộ mô tả tệp sau OS.RENAME []

Đã trả lời ngày 30 tháng 7 năm 2021 lúc 8:30Jul 30, 2021 at 8:30

Sida Zhousida ZhouSida Zhou

3.2712 huy hiệu vàng26 Huy hiệu bạc46 Huy hiệu đồng2 gold badges26 silver badges46 bronze badges

1

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

with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']
3,
with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']
4,
with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']
5 và
with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']
6 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.
with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']
7 và
with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']
8 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:

________ 39 ________ 40 [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, *, 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ư

with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']
7. 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
with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']
7. 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à

with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...
2 để 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
with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...
3.

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

with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']
7.

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

with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...
5 là đối tượng tệp thực tế.

Cờ

with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...
6 đượ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

with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...
7 với đối số
with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...
8.auditing event
with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...
7 with argument
with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...
8.

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

with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...
6 hiện được sử dụng nếu có.The
with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...
6 flag is now used if available.

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

A[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
>>> t = tempfile.TemporaryDirectory[]
>>> print[t]

>>> print[t.name]
/tmp/tmpqign52ry
2, 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
>>> t = tempfile.TemporaryDirectory[]
>>> print[t]

>>> print[t.name]
/tmp/tmpqign52ry
3 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
with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...
5 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 tempfile
>>> t = tempfile.TemporaryDirectory[]
>>> print[t]

>>> print[t.name]
/tmp/tmpqign52ry
5, giống như một tệp thông thường.

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

with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...
7 với đối số
with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...
8.auditing event
with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...
7 with argument
with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...
8.

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

A[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
>>> t = tempfile.TemporaryDirectory[]
>>> print[t]

>>> print[t.name]
/tmp/tmpqign52ry
2, 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
>>> t = tempfile.TemporaryDirectory[]
>>> print[t]

>>> print[t.name]
/tmp/tmpqign52ry
3 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
with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...
5 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 tempfile
>>> t = tempfile.TemporaryDirectory[]
>>> print[t]

>>> print[t.name]
/tmp/tmpqign52ry
5, giống như một tệp thông thường.

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

open[name, 'w']
3, 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ó.

Đối tượng được trả về là một đối tượng giống như tệp có thuộc tính

open[name, 'w']
4 là đối tượng
open[name, 'w']
5 hoặc
open[name, 'w']
6 [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
open[name, 'w']
3 đã đượ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 tempfile
>>> t = tempfile.TemporaryDirectory[]
>>> print[t]

>>> print[t.name]
/tmp/tmpqign52ry
5, 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ố

open[name, 'w']
9.the truncate method now accepts a
open[name, 'w']
9 argument.

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

Lớp ________ 39 ________ 71 [hậu tố = không, tiền tố = không[suffix=None, prefix=None, dir=None, ignore_cleanup_errors=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ư

with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']
8. Đố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.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.

Tên thư mục có thể được lấy từ thuộc tính

>>> import tempfile
>>> t = tempfile.TemporaryDirectory[]
>>> print[t]

>>> print[t.name]
/tmp/tmpqign52ry
3 của đối tượng được trả về. Khi đối tượng được trả về được sử dụng làm Trình quản lý ngữ cảnh,
>>> import tempfile
>>> t = tempfile.TemporaryDirectory[]
>>> print[t]

>>> print[t.name]
/tmp/tmpqign52ry
3 sẽ được gán cho mục tiêu của mệnh đề
import os
import tempfile

print 'Building a file name yourself:'
filename = '/tmp/guess_my_name.%s.txt' % os.getpid[]
temp = open[filename, 'w+b']
try:
    print 'temp:', temp
    print 'temp.name:', temp.name
finally:
    temp.close[]
    # Clean up the temporary file yourself
    os.remove[filename]
5 trong câu lệnh
>>> import tempfile
>>> t = tempfile.TemporaryDirectory[]
>>> print[t]

>>> print[t.name]
/tmp/tmpqign52ry
5, nếu có.

Thư mục có thể được làm sạch rõ ràng bằng cách gọi phương thức

import os
import tempfile

print 'Building a file name yourself:'
filename = '/tmp/guess_my_name.%s.txt' % os.getpid[]
temp = open[filename, 'w+b']
try:
    print 'temp:', temp
    print 'temp.name:', temp.name
finally:
    temp.close[]
    # Clean up the temporary file yourself
    os.remove[filename]
7. Nếu bỏ qua_cleanup_errors là đúng, bất kỳ ngoại lệ chưa được xử lý nào trong quá trình dọn dẹp rõ ràng hoặc ẩn [chẳng hạn như
import os
import tempfile

print 'Building a file name yourself:'
filename = '/tmp/guess_my_name.%s.txt' % os.getpid[]
temp = open[filename, 'w+b']
try:
    print 'temp:', temp
    print 'temp.name:', temp.name
finally:
    temp.close[]
    # Clean up the temporary file yourself
    os.remove[filename]
8 xóa các tệp mở trên Windows] sẽ bị bỏ qua và các mục có thể tháo rời còn lại bị xóa trên cơ sở hiệu ứng tốt nhất. Mặt khác, các lỗi sẽ được nêu ra trong bất kỳ việc dọn dẹp ngữ cảnh nào [cuộc gọi ____777, thoát khỏi trình quản lý bối cảnh, khi đối tượng được thu thập rác hoặc trong quá trình tắt phiên dịch].

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

import tempfile, os

with tempfile.NamedTemporaryFile[] as temp_fp:
    os.rename[temp_fp.name, '/tmp/my_custom_name.txt']
    # do stuff here ...

    # do stuff here END ...
    os.rename['/tmp/my_custom_name.txt', temp_fp.name] # finally, rename back
    
0 với đối số
with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...
8.auditing event
import tempfile, os

with tempfile.NamedTemporaryFile[] as temp_fp:
    os.rename[temp_fp.name, '/tmp/my_custom_name.txt']
    # do stuff here ...

    # do stuff here END ...
    os.rename['/tmp/my_custom_name.txt', temp_fp.name] # finally, rename back
    
0 with argument
with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...
8.

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.

________ 39 ________ 83 [hậu tố = không, tiền tố = none, dir = none, text = false] ¶[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ờ

import tempfile, os

with tempfile.NamedTemporaryFile[] as temp_fp:
    os.rename[temp_fp.name, '/tmp/my_custom_name.txt']
    # do stuff here ...

    # do stuff here END ...
    os.rename['/tmp/my_custom_name.txt', temp_fp.name] # finally, rename back
    
4 cho
import tempfile, os

with tempfile.NamedTemporaryFile[] as temp_fp:
    os.rename[temp_fp.name, '/tmp/my_custom_name.txt']
    # do stuff here ...

    # do stuff here END ...
    os.rename['/tmp/my_custom_name.txt', temp_fp.name] # finally, rename back
    
5. 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
>>> t = tempfile.TemporaryDirectory[]
>>> print[t]

>>> print[t.name]
/tmp/tmpqign52ry
2, người dùng của
with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']
7 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à

import tempfile, os

with tempfile.NamedTemporaryFile[] as temp_fp:
    os.rename[temp_fp.name, '/tmp/my_custom_name.txt']
    # do stuff here ...

    # do stuff here END ...
    os.rename['/tmp/my_custom_name.txt', temp_fp.name] # finally, rename back
    
8, 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ố.
with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']
7 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à

import tempfile, os

with tempfile.NamedTemporaryFile[] as temp_fp:
    os.rename[temp_fp.name, '/tmp/my_custom_name.txt']
    # do stuff here ...

    # do stuff here END ...
    os.rename['/tmp/my_custom_name.txt', temp_fp.name] # finally, rename back
    
8, 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
>>> 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 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
2, nếu phù hợp.

Nếu dir không phải là

import tempfile, os

with tempfile.NamedTemporaryFile[] as temp_fp:
    os.rename[temp_fp.name, '/tmp/my_custom_name.txt']
    # do stuff here ...

    # do stuff here END ...
    os.rename['/tmp/my_custom_name.txt', temp_fp.name] # finally, rename back
    
8, 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
>>> 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.

Nếu bất kỳ hậu tố, tiền tố và dir không phải là

import tempfile, os

with tempfile.NamedTemporaryFile[] as temp_fp:
    os.rename[temp_fp.name, '/tmp/my_custom_name.txt']
    # do stuff here ...

    # do stuff here END ...
    os.rename['/tmp/my_custom_name.txt', temp_fp.name] # finally, rename back
    
8, 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
>>> 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.

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.

with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']
7 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
import tempfile, os

with tempfile.NamedTemporaryFile[] as temp_fp:
    os.rename[temp_fp.name, '/tmp/my_custom_name.txt']
    # do stuff here ...

    # do stuff here END ...
    os.rename['/tmp/my_custom_name.txt', temp_fp.name] # finally, rename back
    
5] 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

with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...
7 với đối số
with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...
8.auditing event
with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...
7 with argument
with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...
8.

Đã 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à

import tempfile, os

with tempfile.NamedTemporaryFile[] as temp_fp:
    os.rename[temp_fp.name, '/tmp/my_custom_name.txt']
    # do stuff here ...

    # do stuff here END ...
    os.rename['/tmp/my_custom_name.txt', temp_fp.name] # finally, rename back
    
8 để 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
import tempfile, os

with tempfile.NamedTemporaryFile[] as temp_fp:
    os.rename[temp_fp.name, '/tmp/my_custom_name.txt']
    # do stuff here ...

    # do stuff here END ...
    os.rename['/tmp/my_custom_name.txt', temp_fp.name] # finally, rename back
    
8 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.

________ 39 ________ 29 [hậu tố = không, tiền tố = không, 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

with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']
8 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

with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']
7.

with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']
8 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

import tempfile, os

with tempfile.NamedTemporaryFile[] as temp_fp:
    os.rename[temp_fp.name, '/tmp/my_custom_name.txt']
    # do stuff here ...

    # do stuff here END ...
    os.rename['/tmp/my_custom_name.txt', temp_fp.name] # finally, rename back
    
0 với đối số
with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...
8.auditing event
import tempfile, os

with tempfile.NamedTemporaryFile[] as temp_fp:
    os.rename[temp_fp.name, '/tmp/my_custom_name.txt']
    # do stuff here ...

    # do stuff here END ...
    os.rename['/tmp/my_custom_name.txt', temp_fp.name] # finally, rename back
    
0 with argument
with tempfile.TemporaryDirectory[] as temp_dir:
    # open your files here
    named_file = open[os.path.join[temp_dir, "myname.txt"], 'w']

    # do what you want with file...

# directory and files get automatically deleted here...
8.

Đã 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à

import tempfile, os

with tempfile.NamedTemporaryFile[] as temp_fp:
    os.rename[temp_fp.name, '/tmp/my_custom_name.txt']
    # do stuff here ...

    # do stuff here END ...
    os.rename['/tmp/my_custom_name.txt', temp_fp.name] # finally, rename back
    
8 để 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
import tempfile, os

with tempfile.NamedTemporaryFile[] as temp_fp:
    os.rename[temp_fp.name, '/tmp/my_custom_name.txt']
    # do stuff here ...

    # do stuff here END ...
    os.rename['/tmp/my_custom_name.txt', temp_fp.name] # finally, rename back
    
8 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.

________ 39 ________ 111 ​​[][]

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

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

    def __init__[self, file, name, delete=True]:
            self.file = file
            self.name = name
            self.delete = delete
            self._closer = _TemporaryFileCloser[file, name, delete]
    
    12.
    def __init__[self, file, name, delete=True]:
            self.file = file
            self.name = name
            self.delete = delete
            self._closer = _TemporaryFileCloser[file, name, delete]
    
    12 environment variable.

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

    def __init__[self, file, name, delete=True]:
            self.file = file
            self.name = name
            self.delete = delete
            self._closer = _TemporaryFileCloser[file, name, delete]
    
    13.
    def __init__[self, file, name, delete=True]:
            self.file = file
            self.name = name
            self.delete = delete
            self._closer = _TemporaryFileCloser[file, name, delete]
    
    13 environment variable.

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

    def __init__[self, file, name, delete=True]:
            self.file = file
            self.name = name
            self.delete = delete
            self._closer = _TemporaryFileCloser[file, name, delete]
    
    14.
    def __init__[self, file, name, delete=True]:
            self.file = file
            self.name = name
            self.delete = delete
            self._closer = _TemporaryFileCloser[file, name, delete]
    
    14 environment variable.

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

    • Trên Windows, các thư mục

      def __init__[self, file, name, delete=True]:
              self.file = file
              self.name = name
              self.delete = delete
              self._closer = _TemporaryFileCloser[file, name, delete]
      
      15,
      def __init__[self, file, name, delete=True]:
              self.file = file
              self.name = name
              self.delete = delete
              self._closer = _TemporaryFileCloser[file, name, delete]
      
      16,
      def __init__[self, file, name, delete=True]:
              self.file = file
              self.name = name
              self.delete = delete
              self._closer = _TemporaryFileCloser[file, name, delete]
      
      17 và
      def __init__[self, file, name, delete=True]:
              self.file = file
              self.name = name
              self.delete = delete
              self._closer = _TemporaryFileCloser[file, name, delete]
      
      18, theo thứ tự đó.

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

      def __init__[self, file, name, delete=True]:
              self.file = file
              self.name = name
              self.delete = delete
              self._closer = _TemporaryFileCloser[file, name, delete]
      
      19,
      def __init__[self, file, name, delete=True]:
              self.file = file
              self.name = name
              self.delete = delete
              self._closer = _TemporaryFileCloser[file, name, delete]
      
      20 và
      def __init__[self, file, name, delete=True]:
              self.file = file
              self.name = name
              self.delete = delete
              self._closer = _TemporaryFileCloser[file, name, delete]
      
      21, theo thứ tự đó.

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

def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
22 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ị

def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
22 nào bất kể loại miễn là nó không phải là
import tempfile, os

with tempfile.NamedTemporaryFile[] as temp_fp:
    os.rename[temp_fp.name, '/tmp/my_custom_name.txt']
    # do stuff here ...

    # do stuff here END ...
    os.rename['/tmp/my_custom_name.txt', temp_fp.name] # finally, rename back
    
8.Always returns a str. Previously it would return any
def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
22 value regardless of type so long as it was not
import tempfile, os

with tempfile.NamedTemporaryFile[] as temp_fp:
    os.rename[temp_fp.name, '/tmp/my_custom_name.txt']
    # do stuff here ...

    # do stuff here END ...
    os.rename['/tmp/my_custom_name.txt', temp_fp.name] # finally, rename back
    
8.

________ 39 ________ 126 [][]

Giống như

def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
27 nhưng giá trị trả về có tính bằng byte.

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

________ 39 ________ 129 [][]

Trả về tiền tố tệp được sử dụng để tạo các tệp tạm thời. Điều này không chứa thành phần thư mục.

________ 39 ________ 131 [][]

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
1 nhưng giá trị trả về là trong byte.

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

________ 39 ________ 129 []

Trả về tiền tố tệp được sử dụng để tạo các tệp tạm thời. Điều này không chứa thành phần thư mục.

________ 39 ________ 131 []path-like object.

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
1 nhưng giá trị trả về là trong byte.

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

def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
27. 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.

________ 39 ________ 135¶

Khi được đặt thành một giá trị khác với
import tempfile, os

with tempfile.NamedTemporaryFile[] as temp_fp:
    os.rename[temp_fp.name, '/tmp/my_custom_name.txt']
    # do stuff here ...

    # do stuff here END ...
    os.rename['/tmp/my_custom_name.txt', temp_fp.name] # finally, rename back
    
8, 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.

Nếu

def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
22 là
import tempfile, os

with tempfile.NamedTemporaryFile[] as temp_fp:
    os.rename[temp_fp.name, '/tmp/my_custom_name.txt']
    # do stuff here ...

    # do stuff here END ...
    os.rename['/tmp/my_custom_name.txt', temp_fp.name] # finally, rename back
    
8 [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ừ
>>> 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, nó sẽ được khởi tạo theo thuật toán được mô tả trong
def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
27.

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

Ghi chú

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

def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
22 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à
with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']
7 và
with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']
8 thay đổi thành byte khi không có
def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
44,
def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
45 hoặc
def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
46 đối số 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ụ;[suffix='', prefix='tmp', dir=None]

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

def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
47:Use
with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']
7 instead.

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

def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
48 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
def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
48 và lần thử 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
with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']
7 và các chức năng khác được mô tả ở trên.

________ 39 ________ 152 [hậu tố = '', tiền tố = 'tmp', dir = none] ¶

def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
0

Thay thế từ phiên bản 2.3: sử dụng
with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']
7 thay thế.

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

with tempfile.NamedTemporaryFile[dir=os.getcwd[]] as f:
    f.write[b'foobar']
    f.flush[]
    f._closer.delete = False
    os.rename[f.name, 'foobar']
7, ngoại trừ tên tệp byte,
def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
55 và
def __init__[self, file, name, delete=True]:
        self.file = file
        self.name = name
        self.delete = delete
        self._closer = _TemporaryFileCloser[file, name, delete]
56 không được hỗ trợ..

Cảnh báo

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

Làm cách nào để tạo một tệp CSV tạm thời trong Python?

Tạo một tệp tạm thời Tệp được tạo bằng hàm tạm thời []. Theo mặc định, tệp được mở ở chế độ W+B, nghĩa là chúng ta có thể đọc và ghi vào tệp mở. Chế độ nhị phân được sử dụng để các tệp có thể hoạt động với tất cả các loại dữ liệu. Tệp này có thể không có tên hiển thị thích hợp trong hệ thống tệp.The file is created using the TemporaryFile[] function. By default, the file is opened in w+b mode, that is, we can both read and write to the open file. Binary mode is used so that files can work with all types of data. This file may not have a proper visible name in the file system.

Tempfile có tên làTemdyfile [] là gì?

Mã nguồn: 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ợ. Tạm thờifile, catureTemingerFile, tạm thời và tementdirectory và spooledtemdyfile 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.This module creates temporary files and directories. It works on all supported platforms. TemporaryFile , NamedTemporaryFile , TemporaryDirectory , and SpooledTemporaryFile are high-level interfaces which provide automatic cleanup and can be used as context managers.

Làm cách nào để tạo tệp TMP?

Để chèn một tên tệp tạm thời mới:..

Trong một hành động ghi vào tệp trong một bước, nhấp chuột phải vào trường tệp ..

Nhấp vào Tên tệp> Tên tệp mới. Cửa sổ thuộc tính FileName Mở ..

Xác định các thuộc tính cho tệp tạm thời: Tên: Cung cấp tên cho tệp tạm thời [ví dụ: báo cáo]. ....

Bấm OK ..

Bài Viết Liên Quan

Chủ Đề