S
S
Stanislav Karpov2014-07-28 13:22:24
Python
Stanislav Karpov, 2014-07-28 13:22:24

What is the best way to create an empty file in Python 3?

Method 1

with open('textfile_1.txt', 'tw', encoding='utf-8') as f:
    pass

Method 2
open('textfile_2.txt', 'tw', encoding='utf-8')
Method 3
f = open('textfile_3.txt', 'tw', encoding='utf-8')
f.close()

Which way is better and why? What other ways are there?
Of particular interest is the description of the operation of the second method. The open function will create a file object, but since it's not saved anywhere, will the interpreter delete it? That is, then the file will be immediately available for reading / editing / deleting, but already to another command / program?
Python 3.4, Windows 8.1

Answer the question

In order to leave comments, you need to log in

3 answer(s)
X
xandox, 2014-07-28
@stkrp

I would suggest such an option
open (..). close ()
and the file is closed, and in one line and without clever constructions.
As for errors, all options in this regard are the same.

Y
yttrium, 2014-07-28
@yttrium

Contexts are more in line with zen and also ensure that the file is closed when an error occurs. (this is the first way)

B
BSergius, 2017-09-20
@BSergius

with open(storage_path, 'w') as f:
    ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question