Python, how to create an empty file

To create a file, useopen()Global function.

It accepts 2 parameters: file path andmode.

you can use itaAs a mode, tell Python to open the file in itAppend mode:

file = '/Users/flavio/test.txt'

open(file, ‘a’).close()

#or

open(file, mode=‘a’).close()

If the file already exists, its content will not be modified. To clear its contents, usewChange to mark:

open(file, 'w').close()

#or

open(file, mode=‘w’).close()

When opening a file, you must remember to close it after you finish using it. In this case, we will close it immediately because our goal is to create an empty file.

Remember to close the file, otherwise it will remain open until the end of the program, and then the program will automatically close.

Or you can usewith:

with open(file, mode='a'): pass

This will automatically close the file.

Creating a file can triggerOSErrorException (for example, if the disk is full), then we use a try block to catch it and handle the problem gracefully by printing an error message:

file = '/Users/flavio/test.txt'

try: open(file, ‘a’).close() except OSError: print(‘Failed creating the file’) else: print(‘File created’)


More python tutorials: