Python - Create New File


Python - Create New File

To create a new file with Python, call open() method with the filename as first argument, and "x" as second argument.

The syntax to create a file with a specific file name is given below.

myfile = open("complete_filepath", "x")

The second argument specifies the mode to open a file with. And "x" specifies to open a file in exclusive creation mode.

Examples

1. Create a New File using open()

In the following example, we will create a new file named sample.txt.

Python Program

#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.

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.

Python Program

f = open("sample.txt", "x")
f.close

You will get FileExistsError with a similar error message as shown below.

Output

Traceback (most recent call last):
  File "example.py", line 1, in <module>
    f = open("sample.txt", "x")
FileExistsError: [Errno 17] File exists: 'sample.txt'

Summary

Concluding this tutorial of Python File Operations, we learned how to create a new file in Python using open() function, with the help of well detailed example programs.