Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify text mode in Python's tempfile.TemporaryFile()?

In the documentation, TemporaryFile() mentions

The returned object is a file-like object whose _file attribute is either an io.BytesIO or io.StringIO object (depending on whether binary or text mode was specified)...

However, as of Python 3.6, there is no text=True method of asking for text mode. How does one do it?

like image 262
Charles Merriam Avatar asked Mar 05 '17 18:03

Charles Merriam


People also ask

How do I write a Tempfile?

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.

How does Tempfile work in Python?

Tempfile is a Python module used in a situation, where we need to read multiple files, change or access the data in the file, and gives output files based on the result of processed data. Each of the output files produced during the program execution was no longer needed after the program was done.

What is Tempfile Mkdtemp ()?

tempfile. mkdtemp (suffix=None, prefix=None, dir=None) 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.

What is Tempfile used for?

Alternatively referred to as a foo file, a temporary file or temp file is a file created to hold information while a file's being created or modified. After the program is closed, the temporary file is deleted. Temporary files store and move data, manage settings, help recover lost data, and manage multiple users.


1 Answers

TemporaryFile signature:

 tempfile.TemporaryFile(mode='w+b', buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None)

We are interested in a mode parameter. The last symbol is 'b', which means binary mode. If you pass mode='wt', it will be opened in a text mode.

All modes are described on this page: https://docs.python.org/3/library/functions.html#open

like image 55
leovp Avatar answered Oct 05 '22 22:10

leovp