Python

Python Menu

The key function for working with files in Python is the open() function. The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

  • "r" - Read - Default value. Opens a file for reading, error if the file does not exist
  • "a" - Append - Opens a file for appending, creates the file if it does not exist
  • "w" - Write - Opens a file for writing, creates the file if it does not exist
  • "x" - Create - Creates the specified file, returns an error if the file exists

In addition, you can specify if the file should be handled as binary or text mode

  • "t" - Text - Default value. Text mode
  • "b" - Binary - Binary mode (e.g. images)

To open a file for reading it is enough to specify the name of the file:

f = open("myFile.txt")

Open a File

Assume we have the following file, located in the same folder as Python:

# myFile.txt
Hello! Welcome to Python!
This file is for testing purposes.
Good Luck!

To open the file, use the built-in open() function.

The open() function returns a file object, which has a read() method for reading the content of the file:

f = open("myFile.txt", "r")
print(f.read())

Output:

C:\Users\My Name>python demo_file_open.py
Hello! Welcome to Python!
This file is for testing purposes.
Good Luck!

If the file is located in a different location, you will have to specify the file path:

f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())

Read Only Parts of the File

By default, the read() method returns the whole text, but you can also specify how many characters you want to return.

Return the first 5 characters of the file:

f = open("myFile.txt", "r")
print(f.read(5))

Write to an Existing File

To write to an existing file, you must add a parameter to the open() function:

  • "a" - Append - will append to the end of the file
  • "w" - Write - will overwrite any existing content

Open the file "myFile.txt" and append content to the file:

f = open("myFile.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:
f = open("myFile.txt", "r")
print(f.read())

Open the file "myFile.txt" and overwrite the content:

f = open("myFile.txt", "w")
# the "w" method will overwrite the entire file
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the appending:
f = open("myFile.txt", "r")
print(f.read())

Create a New File

To create a new file in Python, use the open() method, with one of the following parameters:

  • "x" - Create - will create a file, returns an error if the file exist
  • "a" - Append - will create a file if the specified file does not exist
  • "w" - Write - will create a file if the specified file does not exist

Create a file called "myFile.txt":

f = open("myFile.txt", "x")

Create a new file if it does not exist:

f = open("myFile.txt", "w")

Delete a File

To delete a file, you must import the OS module, and run its os.remove() function:

Remove the file "myFile.txt":

import os
os.remove("myFile.txt")

Check if File exist

To avoid getting an error, you might want to check if the file exists before you try to delete it.

Check if file exists, then delete it:

import os
if os.path.exists("demofile.txt"):
    os.remove("demofile.txt")
else:
    print("The file does not exist")

Delete Folder

To delete an entire folder, use the os.rmdir() method:

Remove the folder "myfolder":
import os
os.rmdir("myfolder")
  • Note: You can only remove empty folders.

Introduction

Python Basics

Python Advance

Data Science Python Tutorials

Python Functions and Methods