Files

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 to these, we can specify if the file should be handled as binary or text mode.

  • "t" - Text - Default value
  • "b" - Binary - Binary mode

To open a file for reading

f = open("test.txt")

or

f = open("demofile.txt", "r")

or 

f = open("demofile.txt", "rt")

Read the File

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

Suppose I have file test.txt with the below text

test.txt

This is a Python class.
This file is for testing purpose.

Example

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

Output:
This is a Python class.  
This file is for testing purpose.

If the file is available in the different location, we need to specify the path.

Example

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

Read only parts of the File

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

Example

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

Output:
This 

Read Lines

We can return one line by using readline() method.

Example

f = open("test.txt", "r")
print(f.readline())

Output:
This is a Python class.

To read multiple lines, we need to call readline() method multiple times.

Example

f = open("test.txt", "r")
print(f.readline())
print(f.readline())

Output:
This is a Python class.
This file is for testing purpose.

By looping through the lines of the file, we can read the whole file, line by line.

Example

f = open("test.txt", "r")
for x in f:
  print(x)

Output:
This is a Python class.
This file is for testing purpose.

Close the File.

We need to close the file, when we are done using the file.

Closing the file

f = open("test.txt", "r")
print(f.readline())
f.close()

Output:
This is a Python class

Write to an Existing File

In order to write to an existing File, we need to mention "a" (to append) or "w" (to overwrite) as a parameter to the open() function.

Example

f = open("test.txt", "a")
f.write("\nNow the file has more content!")
f.close()

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

Output:
This is a Python class.
This file is for testing purpose.
Now the file has more content!

"w" parameter will overwrite the whole content of the file

Example

f = open("test.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the appending:
f = open("test.txt", "r")
print(f.read())
Output:
Woops! I have deleted the content!

Create a New File

In order to create a file, we need to add "x" (to create) or "a" (to create, if the file does not exist) or "w" (to create, if the file does not exist).

Example

f = open("test1.txt", "x")
A new empty file will be created.

Delete a File

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

Example

import os

os.remove("test1.txt")

If the file does not exists, os.remove() will throw an error.

Check if File exist

To avoid getting an error, we can check if the file exists before we try to delete it

Example

import os

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

Delete Folder

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

Example

import os
os.rmdir("myfolder")

This removes entire folder 'myfolder'