Python – Create New File
To create a new file with Python, use open() method with “x” as second parameter and the filename as first parameter.
myfile = open("complete_filepath", "x")
The open() method with options shown in the above code snippet creates an empty file.
Example 1: Create a New File using open()
In the following example, we will create a new file named sample.txt.
#open file f = open("sample.txt", "x") #close file f.close
A new file will be created in the present working directory. You can also provide a complete path to the file if you would like your file to be created at an absolute path in the computer.
Example 2: Create a New File with the same name as that of existing file
In the following example, we will try creating a new file sample.txt. But this file is already present in the same location.
f = open("sample.txt", "x") f.close
You will get FileExistsError with a similar stack trace as below.
Traceback (most recent call last): File "example.py", line 1, in <module> f = open("sample.txt", "x") FileExistsError: [Errno 17] File exists: 'sample.txt'
Concluding this tutorial of Python Examples, we learned how to create a new file in Python using open() function, with the help of well detailed example programs.