Python with temporary file

Модуль 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 закрывается, файл также полностью удаляется из системы.

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

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

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

Читайте также:  Header colors in css

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

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

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

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

Нам нужно было только вызвать функцию 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 для наших программ и приложений. Мы также увидели, как мы можем создавать файлы, которые могут охватывать несколько процессов, и увидели, как мы можем предоставить суффикс префикса для имен файлов, чтобы они легко указывали, какие данные они содержат.

Источник

Python Tempfile Module to Work with Temporary Files and Directories

Python Tempfile

In this tutorial, we’ll delve into the powerful Python tempfile module, an essential tool for creating, managing, and working with temporary files and directories in your applications.

Читайте также:  Css disable pointer events

This guide covers key module methods, such as TemporaryFile(), TemporaryDirectory(), and NamedTemporaryFile(), and how they enable secure and efficient handling of temporary data in a Python environment.

By understanding the tempfile module’s capabilities, you can harness its potential to enhance your software’s reliability and performance. Let’s get started!

The Python tempfile module lets you create and manage temporary files and directories easily. You can work with methods like TemporaryFile(), TemporaryDirectory(), or NamedTemporaryFile() to create temporary files and directories, which are automatically deleted when closed or when your program finishes.

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

import tempfile # Create a temporary file using tempfile.TemporaryFile() temp = tempfile.TemporaryFile() # Retrieve the directory where temporary files are stored temp_dir = tempfile.gettempdir() print(f"Temporary files are stored at: ") print(f"Created a tempfile object: ") print(f"The name of the temp file is: ") # Close and clean up the temporary file automatically temp.close()
Temporary files are stored at: /tmp Created a tempfile object: The name of the temp file is: 3

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.

ls: cannot access '3': No such file or directory

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.

tempfile.TemporaryDirectory(suffix=None, prefix=None, dir=None)

The directory names are random, so you can specify an optional suffix and/or prefix to identify them as part of your program.

Читайте также:  Javascript this object type

Again, to ensure safe deletion of the directory after the relevant code completes, we can use a context manager to securely wrap this!

import tempfile with tempfile.TemporaryDirectory() as tmpdir: # The context manager will automatically delete this directory after this section print(f"Created a temporary directory: ") print("The temporary directory is deleted")
Created a temporary directory: /tmp/tmpa3udfwu6 The temporary directory is deleted

Again, to verify this, you can try to go to the relevant directory path, which won’t exist!

Interacting with Temporary Files: Reading and Writing

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!

import tempfile with tempfile.TemporaryFile() as fp: name = fp.name fp.write(b'Hello from AskPython!') # Write a byte string using fp.write() fp.seek(0) # Go to the start of the file content = fp.read() # Read the contents using fp.read() print(f"Content of file : ") print("File is now deleted")

Let’s now look at the output.

Content of file 3: b'Hello from AskPython!' File is now deleted

Indeed, we were able to easily read and write from/to temporary files too.

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

import tempfile # We create a named temporary file using tempfile.NamedTemporaryFile() temp = tempfile.NamedTemporaryFile(suffix='_temp', prefix='askpython_') print(f"Created a Named Temporary File ") temp.close() print("File is deleted")
Created a Named Temporary File /tmp/askpython_r2m23q4x_temp File is deleted

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 guide, we explored the tempfile module in Python, which provides an efficient way to create and manage temporary files and directories. This powerful tool is crucial when handling temporary data in software applications. As a developer, how might you benefit from using temporary files in your projects?

References

Источник

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