Tmp python что это
Модуль Python tempfile
Вступление
Временные файлы, или “временные файлы”, в основном используются для хранения промежуточной информации на диске для приложения. Эти файлы обычно создаются для различных целей, таких как временное резервное копирование или если приложение имеет дело с большим набором данных, превышающим объем памяти системы, и т. Д. В идеале эти файлы находятся в отдельном каталоге, который варьируется в разных операционных системах, и имена этих файлов уникальны. Данные, хранящиеся во временных файлах, не всегда требуются после завершения работы приложения, поэтому вы можете захотеть, чтобы эти файлы были удалены после использования.
Создание временного файла
Давайте взглянем на приведенную ниже программу Python, чтобы увидеть, как она работает:
Он напечатает нижеприведенный вывод:
Создайте именованный временный файл
Запуск этого кода приведет к печати вывода, аналогичного следующему:
Предоставление суффикса или префикса к имени
Иногда нам нужно добавить префикс или суффикс к имени временного файла. Это поможет нам идентифицировать все временные файлы, созданные нашей программой.
Запуск этого кода приведет к печати следующих выходных данных:
Поиск расположения временных файлов по умолчанию
Переменная tempfile.tempdir содержит расположение по умолчанию для всех временных файлов. Если значение tempdir равно None или unset, Python будет искать стандартный список каталогов и устанавливает tempdir в первое значение каталога, но только в том случае, если вызывающая программа может создать в нем файл. Ниже приведен список каталогов, которые он будет сканировать, в следующем порядке:
Если вы запустите приведенную выше программу, она выведет результат, подобный следующему:
Вы можете видеть, что первое местоположение временного каталога является системным местоположением каталога, а второе значение временного каталога совпадает с тем, которое мы определили.
Чтение и запись данных из временных файлов
Мы узнали, как создать временный файл, создать временный файл с именем и как создать временный файл с суффиксом и/или префиксом. Теперь давайте попробуем понять, как на самом деле читать и записывать данные из временного файла в Python.
Это выведет выходные данные как ‘hello world!’ так как метод write() принимает входные данные в байтах (отсюда и префикс b в строке).
В отличие от предыдущего примера, на выходе будет выведено “Hello World”.
Создание временного каталога
Он напечатает нижеприведенный вывод:
Создайте безопасный временный файл и каталог
Как вы можете видеть в приведенном ниже примере, пользователь несет ответственность за удаление файла.
Вывод
В этой статье мы изучили различные способы создания временных файлов и каталогов в Python. Вы можете использовать временные файлы в любой программе Python, которую вы хотите. Но просто убедитесь, что вы удалили его, если конкретный используемый метод не удаляет его автоматически сам по себе. Также имейте в виду, что поведение может отличаться в разных операционных системах, например, имена выходных каталогов и имена файлов.
PyMOTW
If you find this information useful, consider picking up a copy of my book, The Python Standard Library By Example.
Page Contents
Navigation
This Page
Examples
The output from all the example programs from PyMOTW has been generated with Python 2.7.8, unless otherwise noted. Some of the features described here may not be available in earlier versions of Python.
If you are looking for examples that work under Python 3, please refer to the PyMOTW-3 section of the site.
Navigation
tempfile – Create temporary filesystem resources.¶
Purpose: | Create temporary filesystem resources. |
---|---|
Available In: | Since 1.4 with major security revisions in 2.3 |
TemporaryFile¶
If your application needs a temporary file to store data, but does not need to share that file with other programs, the best option for creating the file is the TemporaryFile() function. It creates a file, and on platforms where it is possible, unlinks it immediately. This makes it impossible for another program to find or open the file, since there is no reference to it in the filesystem table. The file created by TemporaryFile() is removed automatically when it is closed.
This example illustrates the difference in creating a temporary file using a common pattern for making up a name, versus using the TemporaryFile() function. Notice that the file returned by TemporaryFile() has no name.
By default, the file handle is created with mode ‘w+b’ so it behaves consistently on all platforms and your program can write to it and read from it.
After writing, you have to rewind the file handle using seek() in order to read the data back from it.
If you want the file to work in text mode, set mode to ‘w+t’ when you create it:
The file handle treats the data as text:
NamedTemporaryFile¶
There are situations, however, where having a named temporary file is important. If your application spans multiple processes, or even hosts, naming the file is the simplest way to pass it between parts of the application. The NamedTemporaryFile() function creates a file with a name, accessed from the name attribute.
Even though the file is named, it is still removed after the handle is closed.
mkdtemp¶
Since the directory is not “opened” per se, you have to remove it yourself when you are done with it.
Predicting Names¶
For debugging purposes, it is useful to be able to include some indication of the origin of the temporary files. While obviously less secure than strictly anonymous temporary files, including a predictable portion in the name lets you find the file to examine it while your program is using it. All of the functions described so far take three arguments to allow you to control the filenames to some degree. Names are generated using the formula:
The prefix and suffix arguments are combined with a random string of characters to build the file name, and the dir argument is taken as-is and used as the location of the new file.
Temporary File Location¶
If you don’t specify an explicit destination using the dir argument, the actual path used for the temporary files will vary based on your platform and settings. The tempfile module includes two functions for querying the settings being used at runtime:
gettempdir() returns the default directory that will hold all of the temporary files and gettempprefix() returns the string prefix for new file and directory names.
The value returned by gettempdir() is set based on a straightforward algorithm of looking through a list of locations for the first place the current process can create a file. From the library documentation:
Python searches a standard list of directories and sets tempdir to the first one which the calling user can create files in. The list is:
If your program needs to use a global location for all temporary files that you need to set explicitly but do not want to set through one of these environment variables, you can set tempfile.tempdir directly.
tempfile Standard library documentation for this module. File Access More modules for working with files.
Python HowTo – Using the tempfile Module in Python
Hello everyone! In today’s article, we’ll be looking at how we can use the tempfile module in Python.
This module is very useful when you want to store temporary files. There may be a need to store temporary data from an application point of view, so these files can prove to be very useful!
Python provides us with the tempfile module, which gives us an easy to use interface. Let’s get started.
The tempfile module in Python
This module is a part of the standard library (Python 3.x), so you don’t need to install anything using pip. You can simply import it!
We will look at how we can create temporary files and directories now.
Creating Temporary Files and Directories
The tempfile module gives us the TemporaryFile() method, which will create a temporary file.
Since the file is temporary, other programs cannot access this file directly.
As a general safety measure, Python will automatically delete any temporary files created after it is closed. Even if it remains open, after our program completes, this temporary data will be deleted.
Let’s look at a simple example now.
Output
Let’s now try to find this file, using tempfile.gettempdir() to get the directory where all the temp files are stored.
After running the program, if you go to temp_dir (which is /tmp in my case – Linux), you can see that the newly created file 3 is not there.
This proves that Python automatically deletes these temporary files after they are closed.
Now, similar to creating temporary files, we can also create temporary directories using the tempfile.TemporaryDirectory() function.
The directory names are random, so you can specify an optional suffix and/or prefix to identify them as part of your program.
Again, to ensure safe deletion of the directory after the relevant code completes, we can use a context manager to securely wrap this!
Output
Again, to verify this, you can try to go to the relevant directory path, which won’t exist!
1. Reading and Writing from a Temporary File
Similar to reading or writing from a file, we can use the same kind of function calls to do this from a temporary file too!
Let’s now look at the output.
Output
Indeed, we were able to easily read and write from/to temporary files too.
2. Creating Named Temporary Files
In some situations, named temporary files may be useful to make the files visible to other scripts/processes so that they can access it, while it is not yet closed.
The tempfile.NamedTemporaryFile() is useful for this. This has the same syntax as creating a normal temporary file.
Output
Here, a named temporary file with a prefix of askpython_ and suffix of _temp is created. Again, it will be deleted automatically after it is closed.
Conclusion
In this article, we learned how we can use the tempfile module in Python to deal with temporary files and directories.
Некоторые возможности Python о которых вы возможно не знали
Предисловие
Я очень полюбил Python после того, как прочитал книгу Марка Лутца «Изучаем Python». Язык очень красив, на нем приятно писать и выражать собственные идеи. Большое количество интерпретаторов и компиляторов, расширений, модулей и фреймворков говорит о том, что сообщество очень активно и язык развивается. В процессе изучения языка у меня появилось много вопросов, которые я тщательно гуглил и старался понять каждую непонятую мной конструкцию. Об этом мы и поговорим с вами в этой статье, статья ориентирована на начинающего Python разработчика.
Немного о терминах
Начну пожалуй с терминов, которые часто путают начинающих Python программистов.
List comprehensions или генераторы списков возвращают список. Я всегда путал генераторы списков и выражения — генераторы (но не генераторы выражений!). Согласитесь, по русский звучит очень похоже. Выражения — генераторы это generator expressions, специальные выражения, которые возвращают итератор, а не список. Давайте сравним:
Это две совершенно разные конструкции. Первый возвращает генератор (то есть итератор), второй обычный список.
Generators или генераторы это специальные функции, которые возвращают итератор. Что бы получить генератор нужно возвратить функции значение через yield:
Кстати, в Python 3.3 появилась новая конструкция yield from. Совместное использование yield и for используется настолько часто, что эти две конструкции решили объединить.
Что такое контекстные менеджеры и для чего они нужны?
Контекстные менеджеры это специальные конструкции, которые представляют из себя блоки кода, заключенные в инструкцию with. Инструкция with создает блок используя протокол контекстного менеджера, о котором мы поговорим далее в этой статье. Простейшей функцией, использующей данный протокол является функция open(). Каждый раз, как мы открываем файл нам необходимо его закрыть, что бы вытолкнуть выходные данные на диск (на самом деле Python вызывает метод close() автоматически, но явное его использование является хорошим тоном). Например:
Что бы каждый раз не вызывать метод close() мы можем воспользоваться контекстным менеджером функции open(), который автоматически закроет файл после выхода из блока:
Здесь нам не нужно каждый раз вызывать метод close, что бы вытолкнуть данные в файл. Из этого следует, что контекстный менеджер используется для выполнения каких либо действий до входа в блок и после выхода из него. Но функциональность контекстных менеджеров на этом не заканчивается. Во многих языках программирования для подобных задач используются деструкторы. Но в Python если объект используется где то еще то нет гарантии, что деструктор будет вызван, так как метод __del__ вызывается только в том случае, если все ссылки на объект были исчерпаны:
Решим эту задачу через контекстные менеджеры:
Теперь попробуем вызвать менеджер контекста:
Мы увидели, что произошел гарантированный выход из блока после выполнения нашего кода.
Протокол контекстного менеджера
Мы уже кратко рассмотрели протокол контекстного менеджера написав небольшой класс Hello. Давайте теперь разберемся в протоколе более подробно. Что бы объект стал контекстным менеджером в его класс обязательно нужно включить два метода: __enter__ и __exit__. Первый метод выполняется до входа в блок. Методу можно возвратить текущий экземпляр класса, что бы к нему можно было обращаться через инструкцию as.
Метод __exit__ выполняется после выхода из блока with, и он содержит три параметра — exp_type, exp_value и exp_tr. Контекстный менеджер может вылавливать исключения, которые были возбуждены в блоке with. Мы можем вылавливать только нужные нам исключения или подавлять ненужные.
Переменная exp_type содержит в себе класс исключения, которое было возбуждено, exp_value — сообщение исключения. В примере мы закрываем файл и подавляем исключение IOError посредством возврата True методу __exit__. Все остальные исключения в блоке мы разрешаем. Как только наш код подходит к концу и блок заканчивается вызывается метод self.fp.close(), не зависимо от того, какое исключение было возбуждено. Кстати, внутри блока with можно подавлять и такие исключения как NameError, SyntaxError, но этого делать не стоит.
Протоколы контекстных менеджеров очень просты в использовании, но для обычных задач есть еще более простой способ, который поставляется вместе со стандартной библиотекой питона. Далее мы рассмотрим пакет contextlib.
Пакет contextlib
Создание контекстных менеджеров традиционным способом, то есть написанием классов с методами __enter__ и __exit__ не одна из сложных задач. Но для тривиального кода написание подобных классов требует больше возьни. Для этих целей был придуман декоратор contextmanager(), входящий в состав пакета contextlib. Используя декоратор contextmanager() мы можем из обычной функции сделать контекстный менеджер:
Проверим работоспособность кода:
Попробуем возбудить исключение внутри блока.
Как видно из примера, реализация с использованием классов практически ничем не отличается по функциональности от реализации с использованием декоратора contextmanager(), но использование декоратора намного упрощает наш код.
Еще один интересный пример использования декоратора contextmanager():
Похоже на блоки в руби не так ли?
И напоследок поговорим о вложенных контекстах. Вложенные контексты позволяют управлять несколькими контекстами одновременно. Например:
вход в контекст first
вход в контекст second
внутри блока first second
выход из контекста second
выход из контекста first
Аналогичный код без использования функции nested:
Этот код хоть и похож на предыдущий, в некоторых ситуациях он будет работать не так как нам хотелось бы. Объекты context(‘first’) и context(‘second’) вызываются до входа в блок, поэтому мы не сможем перехватывать исключения, которые были возбуждены в этих объектах. Согласитесь, первый вариант намного компактнее и выглядит красивее. А вот в Python 2.7 и 3.1 функция nested устарела и была добавлена новая синтаксическая конструкция для вложенных контекстов:
range и xrange в Python 2.7 и Python 3
Известно, что Python 2.7 range возвращает список. Думаю все согласятся, что хранить большие объемы данных в памяти нецелесообразно, поэтому мы используем функцию xrange, возвращающий объект xrange который ведет себя почти так же как и список, но не хранит в памяти все выдаваемые элементы. Но меня немного удивило поведение xrange в Python 2.x, когда функции передаются большие значения. Давайте посмотрим на пример:
Python нам говорит о том, что int слишком длинный и он не может быть переконвертирован в C long. Оказывается у Python 2.x есть ограничения на целое число, в этом мы можем убедиться просмотрев константу sys.maxsize:
Вот оно максимальное значение целого числа:
Python аккуратно переконвертировал наше число в long int. Не удивляйтесь, если xrange в Python 2.x будет вести себя иначе при больших значениях.
В Python 3.3 целое число может быть бесконечно большим, давайте проверим:
Конвертирование в long int не произошло. Вот еще пример:
Не очевидное поведение некоторых конструкций
Думаю все согласятся, что простота питона заключена не в легкости его изучении, а в простоте самого языка. Питон красив, гибок и на нем можно писать не только в объектно ориентированном стиле, но и в функциональном. Но о поведении некоторых конструкций, который на первый взгляд кажутся странными необходимо знать. Для начала рассмотрим первый пример.
Каков будет результат выполнения данной конструкции? Неподготовленный разработчик сообщит о результате: [[‘a’], [b’], [c’]]. Но на самом деле мы получаем:
Почему в каждом списке результат дублируется? Дело в том, что оператор умножения создает ссылки внутри нашего списка на один и тот же список. В этом легко убедиться немного дополнив наш пример:
В первом случае все нормально и ссылки на списки разные, а во втором примере мы ссылаемся на один и тот же объект. Из этого следует, что изменение в первом списке повлечет за собой изменение в последующих, так что будьте внимательны.
Второй пример уже рассматривался на хабре, но мне захотелось включить его в статью. Посмотрим на lambda — функцию, которую мы будет прогонять через цикл for, и помещать каждую функцию в словарь:
В пределах lambda функции переменная i замыкается и как бы создается экземпляр еще одной переменной i в блоке lambda — функции, которая является ссылкой на переменную i в цикле for. Каждый раз когда счетчик цикла for меняется, меняются и значения во всех lambda функциях, поэтому мы получаем значение i-1 во всех функциях. Исправить это легко, явно передав lambda функции в качестве первого параметра значение по умолчанию — переменную i:
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.