Что такое temp в питоне

Модуль tempfile в Python, временные файлы и каталоги.

Создание защищенных временных файлов и каталогов для программы.

Модуль tempfile создает временные файлы и каталоги. Работает на всех поддерживаемых платформах. Модуль определяет несколько конструкторов высокого уровня, которые обеспечивают автоматическую очистку и могут использоваться в качестве менеджеров контекста. Функции tempfile.mkstemp() и tempfile.mkdtemp() являются функциями более низкого уровня, которые требуют ручной очистки.

Приложения, которым требуются временные файлы для хранения данных, без необходимости делиться этим файлом с другими программами, должны использовать функцию tempfile.TemporaryFile() для создания файлов. Функция создает файл и на платформах, где это возможно, немедленно отменяет связь с ним. Это делает невозможным для другой программы найти или открыть файл, поскольку в таблице файловой системы нет ссылки на него.

Когда требуется несколько временных файлов, может быть удобнее создать один временный каталог с помощью tempfile.TemporaryDirectory() и открыть все файлы в этом каталоге.

Все вызываемые пользователем функции и конструкторы принимают дополнительные аргументы, которые позволяют напрямую контролировать расположение и имя временных файлов и каталогов. Имена файлов, используемые этим модулем, содержат строку случайных символов, которая позволяет безопасно создавать эти файлы в общих временных каталогах. Для обеспечения обратной совместимости порядок аргументов несколько странный. Для ясности рекомендуется использовать ключевые аргументы.

Примеры:

Вот несколько примеров типичного использования модуля tempfile :

Создать временный файл, используя менеджер контекста

Создать временный каталог с помощью диспетчера контекста

Источник

tempfile — Generate temporary files and directories¶

Source code: Lib/tempfile.py

All the user-callable functions and constructors take additional arguments which allow direct control over the location and name of temporary files and directories. Files names used by this module include a string of random characters which allows those files to be securely created in shared temporary directories. To maintain backward compatibility, the argument order is somewhat odd; it is recommended to use keyword arguments for clarity.

The module defines the following user-callable items:

The resulting object can be used as a context manager (see Examples ). On completion of the context or destruction of the file object the temporary file will be removed from the filesystem.

The returned object is a true file object on POSIX platforms. On other platforms, it is a file-like object whose file attribute is the underlying true file object.

The os.O_TMPFILE flag is used if it is available and works (Linux-specific, requires Linux kernel 3.11 or later).

Changed in version 3.5: The os.O_TMPFILE flag is now used if available.

Changed in version 3.8: Added errors parameter.

This function operates exactly as TemporaryFile() does, except that the file is guaranteed to have a visible name in the file system (on Unix, the directory entry is not unlinked). That name can be retrieved from the name attribute of the returned file-like object. Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later). If delete is true (the default), the file is deleted as soon as it is closed. The returned object is always a file-like object whose file attribute is the underlying true file object. This file-like object can be used in a with statement, just like a normal file.

Changed in version 3.8: Added errors parameter.

The returned object is a file-like object whose _file attribute is either an io.BytesIO or io.TextIOWrapper object (depending on whether binary or text mode was specified) or a true file object, depending on whether rollover() has been called. This file-like object can be used in a with statement, just like a normal file.

Changed in version 3.3: the truncate method now accepts a size argument.

Changed in version 3.8: Added errors parameter.

The directory name can be retrieved from the name attribute of the returned object. When the returned object is used as a context manager, the name will be assigned to the target of the as clause in the with statement, if there is one.

The directory can be explicitly cleaned up by calling the cleanup() method. If ignore_cleanup_errors is true, any unhandled exceptions during explicit or implicit cleanup (such as a PermissionError removing open files on Windows) will be ignored, and the remaining removable items deleted on a “best-effort” basis. Otherwise, errors will be raised in whatever context cleanup occurs (the cleanup() call, exiting the context manager, when the object is garbage-collected or during interpreter shutdown).

Changed in version 3.10: Added ignore_cleanup_errors parameter.

If text is specified and true, the file is opened in text mode. Otherwise, (the default) the file is opened in binary mode.

mkstemp() returns a tuple containing an OS-level handle to an open file (as would be returned by os.open() ) and the absolute pathname of that file, in that order.

Changed in version 3.5: 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 None to cause an appropriate default value to be used.

Creates a temporary directory in the most secure manner possible. There are no race conditions in the directory’s creation. The directory is readable, writable, and searchable only by the creating user ID.

The user of mkdtemp() is responsible for deleting the temporary directory and its contents when done with it.

mkdtemp() returns the absolute pathname of the new directory.

Changed in version 3.5: 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 None to cause an appropriate default value to be used.

Return the name of the directory used for temporary files. This defines the default value for the dir argument to all functions in this module.

Python searches a standard list of directories to find one which the calling user can create files in. The list is:

The directory named by the TMPDIR environment variable.

The directory named by the TEMP environment variable.

The directory named by the TMP environment variable.

A platform-specific location:

As a last resort, the current working directory.

The result of this search is cached, see the description of tempdir below.

Same as gettempdir() but the return value is in bytes.

Return the filename prefix used to create temporary files. This does not contain the directory component.

Same as gettempprefix() but the return value is in bytes.

ExamplesВ¶

Here are some examples of typical usage of the tempfile module:

Deprecated functions and variablesВ¶

A historical way to create temporary files was to first generate a file name with the mktemp() function and then create a file using this name. Unfortunately this is not secure, because a different process may create a file with this name in the time between the call to mktemp() and the subsequent attempt to create the file by the first process. The solution is to combine the two steps and create the file immediately. This approach is used by mkstemp() and the other functions described above.

Deprecated since version 2.3: Use mkstemp() instead.

Источник

The Python tempfile Module

Introduction

Temporary files, or «tempfiles», are mainly used to store intermediate information on disk for an application. These files are normally created for different purposes such as temporary backup or if the application is dealing with a large dataset bigger than the system’s memory, etc. Ideally, these files are located in a separate directory, which varies on different operating systems, and the name of these files are unique. The data stored in temporary files is not always required after the application quits, so you may want these files to be deleted after use.

Python provides a module known as tempfile, which makes creating and handling temporary files easier. This module provides a few methods to create temporary files and directories in different ways. tempfile comes in handy whenever you want to use temporary files to store data in a Python program. Let’s take a look at a couple of different examples on how the tempfile module can be used.

Creating a Temporary File

Suppose your application needs a temporary file for use within the program, i.e. it will create one file, use it to store some data, and then delete it after use. To achieve this, we can use the TemporaryFile() function.

This function will create one temporary file to the default tempfile location. This location may be different between operating systems. The best part is that the temporary file created by TemporaryFile() will be removed automatically whenever it the file is closed. Also, it does not create any reference to this file in the system’s filesystem table. This makes it private to the current application i.e. no other program will be able to open the file.

Let’s take a look at the below Python program to see how it works:

It will print the below output:

One thing we should point out is that the file created using the TemporaryFile() function may or may not have a visible name in the file system. On Unix, the directory entry for the file is removed automatically after it is created, although this is not supported on other platforms. Normally TemporaryFile() is the ideal way to create one temporary storage area for any program in Python.

Create a Named Temporary File

Running this code will print output similar to the following:

Providing a Suffix or Prefix to the Name

Sometimes we need to add a prefix or suffix to a temp-file’s name. It will help us to identify all temp files created by our program.

To achieve this, we can use the same NamedTemporaryFile function defined above. The only thing we need to add is two extra parameters while calling this function: suffix and prefix

Running this code will print the following output:

So, if we will pass the two extra arguments suffix and prefix to the NamedTemporaryFile() function, it will automatically add those in the start and end of the file name.

Finding the Default Location of Temp Files

The tempfile.tempdir variable holds the default location for all temporary files. If the value of tempdir is None or unset, Python will search a standard list of directories and sets tempdir to the first directory value, but only if the calling program can create a file in it. The following are the list of directories it will scan, in this order:

If you will run the above program, it will print an output similar to the following:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

You can see that the first temp directory location is the system-provided directory location and the second temp directory is the same value as the one that we have defined.

Reading and Writing Data from Temp Files

We have learned how to create a temporary file, create a temporary file with a name, and how to create a temporary file with a suffix and/or prefix. Now, let’s try to understand how to actually read and write data from a temporary file in Python.

Reading and writing data from a temporary file in Python is pretty straightforward. For writing, you can use the write() method and for reading, you can use the read() method. For example:

This will print the output as b’Hello world!’ since the write() method takes input data in bytes (hence the b prefix on the string).

If you want to write text data into a temp file, you can use the writelines() method instead. For using this method, we need to create the tempfile using w+t mode instead of the default w+b mode. To do this, a mode param can be passed to TemporaryFile() to change the mode of the created temp file.

Unlike the previous example, this will print «Hello World» as the output.

Create a Temporary Directory

If your program has several temporary files, it may be more convenient to create one temporary directory and put all of your temp files inside of it. To create a temporary directory, we can use the TemporaryDirectory() function. After all temp files are closed, we need to delete the directory manually.

It will print the below output:

Create a Secure Temporary File and Directory

As you can see in the example below, the user is responsible for deleting the file.

Conclusion

In this article we have learned different ways to create temporary files and directories in Python. You can use temp files in any Python program you want. But just make sure to delete it if the particular method used doesn’t automatically delete it on its own. Also keep in mind that behavior may different between operating systems, like the output directory names and file names.

All of these functions we have explained above works with many different arguments, although we have not covered in detail what type of arguments each function takes. If you want to learn more about the tempfile module, you should check out the Python 3 official documentation.

Источник

Модуль Python tempfile

Вступление

Временные файлы, или “временные файлы”, в основном используются для хранения промежуточной информации на диске для приложения. Эти файлы обычно создаются для различных целей, таких как временное резервное копирование или если приложение имеет дело с большим набором данных, превышающим объем памяти системы, и т. Д. В идеале эти файлы находятся в отдельном каталоге, который варьируется в разных операционных системах, и имена этих файлов уникальны. Данные, хранящиеся во временных файлах, не всегда требуются после завершения работы приложения, поэтому вы можете захотеть, чтобы эти файлы были удалены после использования.

Создание временного файла

Давайте взглянем на приведенную ниже программу Python, чтобы увидеть, как она работает:

Он напечатает нижеприведенный вывод:

Создайте именованный временный файл

Запуск этого кода приведет к печати вывода, аналогичного следующему:

Предоставление суффикса или префикса к имени

Иногда нам нужно добавить префикс или суффикс к имени временного файла. Это поможет нам идентифицировать все временные файлы, созданные нашей программой.

Запуск этого кода приведет к печати следующих выходных данных:

Поиск расположения временных файлов по умолчанию

Переменная tempfile.tempdir содержит расположение по умолчанию для всех временных файлов. Если значение tempdir равно None или unset, Python будет искать стандартный список каталогов и устанавливает tempdir в первое значение каталога, но только в том случае, если вызывающая программа может создать в нем файл. Ниже приведен список каталогов, которые он будет сканировать, в следующем порядке:

Если вы запустите приведенную выше программу, она выведет результат, подобный следующему:

Вы можете видеть, что первое местоположение временного каталога является системным местоположением каталога, а второе значение временного каталога совпадает с тем, которое мы определили.

Чтение и запись данных из временных файлов

Мы узнали, как создать временный файл, создать временный файл с именем и как создать временный файл с суффиксом и/или префиксом. Теперь давайте попробуем понять, как на самом деле читать и записывать данные из временного файла в Python.

Это выведет выходные данные как ‘hello world!’ так как метод write() принимает входные данные в байтах (отсюда и префикс b в строке).

В отличие от предыдущего примера, на выходе будет выведено “Hello World”.

Создание временного каталога

Он напечатает нижеприведенный вывод:

Создайте безопасный временный файл и каталог

Как вы можете видеть в приведенном ниже примере, пользователь несет ответственность за удаление файла.

Вывод

В этой статье мы изучили различные способы создания временных файлов и каталогов в Python. Вы можете использовать временные файлы в любой программе Python, которую вы хотите. Но просто убедитесь, что вы удалили его, если конкретный используемый метод не удаляет его автоматически сам по себе. Также имейте в виду, что поведение может отличаться в разных операционных системах, например, имена выходных каталогов и имена файлов.

Источник

Что такое temp в питоне

В стандартной библиотеке Python есть модуль tempfile, который содержит классы и методы для корректной работы с временными файлами и директориями.

Сигнатура: tempfile.TemporaryFile(mode=’w+b’, buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None)

Эта функция создает временный файл в системной директории (разная в различных ОС) и возвращает файлоподобный объект (file-like object). Созданный временный файл будет автоматически удален по закрытию файла или при выходе из контекстного менеджера. Также другие процессы и приложения не смогут получить доступ к этому временному файлу.

print(«Creating one temporary file. «)

temp = tempfile.TemporaryFile() #2

print(«Created file is:», temp) #3

print(«Name of the file is:», temp.name) #4

print(«Closing the temp file»)

Creating one temporary file.

Name of the file is: 4

Closing the temp file

Сигнатура: tempfile.NamedTemporaryFile(mode=’w+b’, buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True)

В прошлом примере было показано, что функция tempfile.TemporaryFile() возвращает файлоподобный объект без имени, но в Python есть и другая функция, которая позволяет создать именованный временный файл.

print(«Creating one named temporary file. «)

print(«Created file is:», temp)

print(«Name of the file is:», temp.name)

print(«Closing the temp file»)

Creating one named temporary file.

Name of the file is: /var/folders/l7/80bx27yx3hx_0_p1_qtjyyd40000gn/T/tmpa3rq8lon

Closing the temp file

Как мы видим, у созданного файла есть имя. Фишка в том, что мы можем сохранить имя временного файла и использовать после закрытия файла или завершения программы (для этого есть аргумент delete=False ).

Сигнатура: tempfile.TemporaryDirectory(suffix=None, prefix=None, dir=None)

Эта функция создает временную директорию. Это может быть удобно, если нужно сохранить несколько временных файлов.

with tempfile.TemporaryDirectory() as tmpdirname:

print(‘Created temporary directory:’, tmpdirname)

# Both the directory and its contents have been deleted

Created temporary directory: /var/folders/l7/80bx27yx3hx_0_p1_qtjyyd40000gn/T/tmpn_ke7_rk

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *