To create a file, useopen()
Global function.
It accepts 2 parameters: file path andmode.
you can use ita
As 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, usew
Change 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 triggerOSError
Exception (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:
- Introduction to Python
- 在macOS上安装Python 3
- Run Python program
- Python 2 and Python 3
- Basics of using Python
- Python data types
- Python operators
- Python string
- Python boolean
- Python numbers
- Python, accepts input
- Python control statements
- Python list
- Python tuple
- Python set
- Python dictionary
- Python functions
- Python objects
- Python loop
- Python module
- Python class
- Python standard library
- Debug Python
- Python variable scope
- Python, accept parameters from the command line
- Python recursion
- Python nested functions
- Python Lambda function
- Python closure
- Python virtual environment
- Use Python to use GoPro as a remote webcam
- Python, how to create a list from a string
- Python decorator
- Python Docstrings
- Python introspection
- Python notes
- Python, how to list files and folders in a directory
- Python, how to check if a number is odd or even
- Python, how to get detailed information of a file
- Python, how to check if a file or directory exists
- Python exception
- Python, how to create a directory
- Python, how to create an empty file
- Python, `with` statement
- Python, create a network request
- Python, use `pip` to install third-party software packages
- Python, read file content