Python temp file path

Модуль Tempfile в Python

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

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

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

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

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

Вот пример программы в Python, которая создает временный файл и очищает его при закрытии TemporaryFile:

import os import tempfile # Using PID in filename filename = '/tmp/journaldev.%s.txt' % os.getpid() # File mode is read write temp = open(filename, 'w+b') try: print('temp: '.format(temp)) print('temp.name: '.format(temp.name)) finally: temp.close() # Clean up the temporary file yourself os.remove(filename) print('TemporaryFile:') temp = tempfile.TemporaryFile() try: print('temp: '.format(temp)) print('temp.name: '.format(temp.name)) finally: # Automatically cleans up the file temp.close()

Посмотрим на результат этой программы:

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

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

Запустив эту программу, вы увидите, что в файловой системе вашего компьютера нет файлов.

Чтение из временного файла

К счастью, чтение всех данных из временного файла – это всего лишь вызов одной функции. Благодаря этому мы можем читать данные, которые мы записываем в файл, не обрабатывая их побайтно и не выполняя сложных операций ввода-вывода.

Давайте посмотрим на фрагмент кода, чтобы продемонстрировать это:

import os import tempfile temp_file = tempfile.TemporaryFile() try: print('Writing data:') temp_file.write(b'This is temporary data.') temp_file.seek(0) print('Reading data: \n\t'.format(temp_file.read())) finally: temp_file.close()

Посмотрим на результат этой программы:

Читайте также:  What is html hypertext markup language является

Чтение временного файла

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

Запись простого текста во временный файл

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

import tempfile file_mode = 'w+t' with tempfile.TemporaryFile(mode=file_mode) as file: file.writelines(['Java\n', 'Python\n']) file.seek(0) for line in file: print(line.rstrip())

Посмотрим на результат этой программы:

Запись простого текста во временный файл

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

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

Давайте посмотрим на фрагмент кода, который использует функцию NamedTemporaryFile() для создания именованного временного файла:

import os import tempfile temp_file = tempfile.NamedTemporaryFile() try: print('temp_file : '.format(temp_file)) print('temp.temp_file : '.format(temp_file.name)) finally: # Automatically deletes the file temp_file.close() print('Does exists? : '.format(os.path.exists(temp_file.name)))

Посмотрим на результат этой программы:

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

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

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

Вот пример программы, которая предоставляет префикс и суффикс в имена файлов:

import tempfile temp_file = tempfile.NamedTemporaryFile(suffix='_temp', prefix='jd_', dir='/tmp',) try: print('temp:', temp_file) print('temp.name:', temp_file.name) finally: temp_file.close()

Посмотрим на результат этой программы:

Временный файл с префиксом и суффиксом

Заключение

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

Источник

Understanding the Python Tempfile Module

Python Tempfile

Hello geeks and welcome to this article, we will cover Python Tempfile(). Along with that, for an overall better understanding, we will also look at its syntax and parameter. Then we will see the application of all the theory parts through a couple of examples.

The Python Tempfile is a standard library used to create temporary files and directories. These kinds of files come really handy when we don’t wish to store data permanently. If we are working with massive data, these files are created with unique names and stored at a default location, varying from os to os. For instance, in windows, the temp folder resides in profile/AppData/Local/Temp while different for other cases.

Читайте также:  Тег label

Creating a Temporary File

import tempfile file = tempfile.TemporaryFile() print(file) print(file.name)

Here, we can see how to create a temporary file using python tempfile(). At first, we have imported the tempfile module, following which we have defined a variable and used our function to create a tempfile. After which, we have used the print statement 2 times 1st to get our file and 2nd to exactly get ourselves the exact filename. The filename is randomly generated and may vary from user to user.

Creating a Named Temporary File

import tempfile file = tempfile.NamedTemporaryFile() print(file) print(file.name)
 C:\Users\KIIT\AppData\Local\Temp\tmpgnp482wy

Here we have to create a named temporary file. The only difference, which is quite evident, is that instead of, Temporary file, we have used NamedTemporaryfile. A random file name is allotted, but it is clearly visible, unlike the previous case. Another thing that can be verified here is the structure profile/AppData/Local/Temp(as mentioned for windows os). As if now, we have seen how to create a temporary file and a named temporary file.

Creating a Temporary Directory

import tempfile dir = tempfile.TemporaryDirectory() print(dir)

Here above we have created a directory. A directory can be defined as a file system structure that contains the location for all the other computer files. Here we can see that there’s just a minute change in syntax when compared to what we were using for creating a temporary file. Here just instead of TemporaryFile, we have used TemporaryDirectory.

Reading and Writing to a Temporary File

import tempfile file = tempfile.TemporaryFile() file.write(b'WELCOME TO PYTHON PPOOL') file.seek(0) print(file.read()) file.close()

Above we can see how to read and write in the temporary files. Here we have first created a temporary file. Following which we have used the write function which is used to write data in a temporary file. You must be wondering what is ‘b’ doing there. The fact is that the temporary files take input by default so ‘b’ out there converts the string into binary. Next, the seek function is used to called to set the file pointer at the starting of the file. Then we have used a read function that reads the content of the temporary file.

Alternative to Python tempfile()

Python tempfile() is great but in this section, we will look at one of the alternatives to it. mkstemp() is a function that does all things you can do with the tempfile but in addition to that, it provides security. Only the user that created that has created the temp file can add data to it. Further, this file doesn’t automatically get deleted when closed.

import tempfile sec_file = tempfile.mkstemp() print(sec_file)

Here we can how to create a temporary file using mkstemp(). Not much syntax change can be seen here only; instead of TemporaryFile(), we have used mkstemp(), and the rest of everything is the same.

Читайте также:  Html stylesheet bold text

Temporary File Location

If you want to locate the file you created using tempfile, you need a path of the directory. This can be obtained by calling gettempdir() method. The following code will help you understand –

import tempfile print(tempfile.gettempdir())
C:\Users\PPool\AppData\Local\Temp

By going to the above-mentioned directory, you can easily get the file you created using Python. Keep in mind that these temporary files are cleared many times, so you might not find your file in this directory after a long time.

General FAQ’s regarding python tempfile()

1. How to find the path of python tempfile()?

Ans. To get the path of a python tempfile(), you need to create a named tempfile, which has already been discussed. In that case, you get the exact path of the tempfile, as in our case, we get «C:\Users\KIIT\AppData\Local\Temp\tmpgnp482wy» .

2. How to perform cleanup for python tempfile()?

Ans. Python itself deletes the tempfile once they are closed.

3. How to create secure python tempfile()?

Ans. In order to create a secure tempfile() we can use the mkstemp() function. As has been discussed in detail already. We know the tempfile created using this can only be edited by creating it. Your permission is also required for someone else to access it.

4. What is the name for python tempfile()?

Ans. If you create a temporary file, then it has no name, as discussed above. Whereas when you create a Named tempfile, a random name is allocated to it, visible in its path.

Conclusion

In this article, we covered the Python tempfile(). Besides that, we have also looked at creating a temporary file, temporary directory, how to read and write in a temp file, and looked at an alternative called mkstemp(). Here we can conclude that this function helps us create a Temporary file in python.

I hope this article was able to clear all doubts. But in case you have any unsolved queries feel free to write them below in the comment section. Done reading this, why not read about the argpartition function next.

Источник

Оцените статью