Hướng dẫn python create empty file
To create a file, use the It accepts 2 parameters: the file path, and the mode. You can use
If the file already exists, its content is not modified. To clear its content, use the
When you open a file, you must remember to close it after you’ve finished working with it. In this case, we close it immediately, as our goal is to create an empty file. Remember to close the file, otherwise it will remain open until the end of the program, when it will be automatically closed. Alternatively, you can use
This will automatically close the file. Creating a file can raise an File handling is a very important concept for any programmer. It can be used for creating, deleting, moving files or to store application data, user configurations, videos, images, etc. Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files.
Creating an empty fileFile handling can also be used for creating a file. Even the file with different extension like
Note: The file is created in the same directory of the script if no path is specified. Example #1: In this example we will create a new file myfile.txt. To verify this we will use
Output: List of directories and files before creation: ['.idea', 'gfg.py', 'venv'] List of directories and files after creation: ['.idea', 'gfg.py', 'myfile.txt', 'venv'] # Example 2: Creating a new file at a specified location. For creating a file at a specified location os module is used. Below is the implementation.
Output: List of directories and files before creation: ['test_nikhil.txt'] List of directories and files after creation: ['myfile.txt', 'test_nikhil.txt'] |