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:
open('file_name/file_path', "access_mode")
Example:
First time opning a file.
first_file = open("readme.txt",'x')
first_file.close()
It will throw an error if file already exists
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 | |
---|---|
x | Used only for the exclusive creation. If throws error, if file already exists. |
w | To create and write to file. If a file already exists, it will truncate the existing file. |
a | It will append the new content to the existing file. |
d | It will create and open a binary file. |
t | It will open the file in text mode. |
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.
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.
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.
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()