Create a File in Python


Create a File

To create a file in python, we simply have to use the open() function with file name and mode.

It will create the file in the current working directory. If the file already exists, it will show an error.

Once we have opened the file and done with our work, make sure to close it. For that, we use filemname.close() method.

Syntax:

In [ ]:
open('file_name/file_path', "access_mode")

Example:

First time opning a file.

In [1]:
first_file = open("readme.txt",'x')
first_file.close()

It will throw an error if file already exists

In [2]:
first_file = open("readme.txt",'x')
first_file.close()

Modes

Below are the modes, that are available to us when we create a new file.

Mode
xUsed only for the exclusive creation. If throws error, if file already exists.
wTo create and write to file. If a file already exists, it will truncate the existing file.
aIt will append the new content to the existing file.
dIt will create and open a binary file.
tIt will open the file in text mode.
File modes

Create and write File

As we have already seen above, we use ‘w’ mode to create and write to the file at the same time. If file already exists, it will truncate the existing file.

In [1]:
file = open("notes.txt", 'w')
file.write("Workout tommow morning.")
file.close()

Check if file already exists

To check if a file already exists, we use os.path.exists(“filename”). Make sure, for this we have to import the os module.

It will create a file as file does not exists.

In [1]:
import os

if os.path.exists("readme.txt"):
    print("We already have readme.txt")
else:
    file = open("readme.txt", 'w')
    file.write("Welcome to Logical Python")
    print("New file created.")
    file.close()

It will display “We already have readme.txt” as we have already created file in above code.

In [2]:
import os

if os.path.exists("readme.txt"):
    print("We already have readme.txt")
else:
    file = open("readme.txt", 'w')
    file.write("Welcome to Logical Python")
    print("New file created.")
    file.close()