circuit

Python File Handling

How to create, read, update and delete files in Python




Python has several functions for file handling: creating, reading, updating, and deleting files.

The key function for working with files in Python is the open() function.

open() Function

In Python you need to give access(such as r,w,a,x) to a file by opening it. You can do it by using the open() function.

open() returns a file object, which has methods(such as read(), readline(), write(), close())and attributes for getting information about and manipulating the opened file.

Syntax

f = open(“demofile.txt”)

The code above is the same as:

f = open(“demofile.txt”, “rt”)

Because "r" for read, and "t" for text are the default values, you do not need to specify them.

Parameters

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)

Open a file and Read its content: read() method

. . .

Assume we have the file demofile.txt, located in the same folder as Python:

Hello! Welcome to demofile.txt
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.

Note: It is a good practice to always close the file when you are done with it.

Read the full content of the file as a string

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

type(f) # f is a file object: _io.TextIOWrapper


data = f.read()

print(data)

type(data)  # the type of data is: str

f.close()

Read only several characters of the file

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

f = open(“demofile.txt”, “r”)
print(f.read(**5**))
f.close()

readline() method: Read only one line of the file:

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

readlines() method: Read multiple lines of the file as a list

By defalut, readlines() function reads until end of the file, and returns a list containing each line in the file as a list item.

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

type(line_list) # list

print(line_list)
f.close()

Then you can output the first several lines by slicing the list.

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

Top_5_lines = line_list[0:5]
print(Top_5_lines)
f.close()

Print each line in the list.

f = open('demofile.txt', 'r+')
for line in f.readlines():
    print line
f.close()

fileObject.readlines(n)

Here n is the hint number, which is used to limit the output.

If the number of bytes returned exceed the hint number, no more lines will be returned. Default value is -1, which means all lines will be returned.

Syntax:

fileObject.readlines(n)

Note: n is the number of characters, not the number of lines. For example:

f = open("demofile.txt", "r")
print(f.readlines(5)) # only the first line will be printed, as the parameter is
f.close()

Open an existing file and write to it: write() method

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

Write: append to the end of the file

f = open(“demofile2.txt”, “a”)
f.write(“Now the file has more content!”)
f.close()

Write: overwrite the content

f = open(“demofile3.txt”, “w”)
f.write(“Woops! I have deleted the content!”)
f.close()

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

"w" - Write: will create a file if the specified file does not exist

Create an empty file

f = open(“myfile.txt”, “x”)
f.close()

Create an empty file and write into it

f = open(“myfile.txt”, “w”)
f.write(“Now the file has more content!”)
f.close()

. . .

Delete

Delete a File: os.remove() function

To delete a file, you must import the OS module, and run its os.remove() function. For example, remove the file “demofile.txt”:

import os
os.remove(“demofile.txt”)

Check if File exist: os.path.exists()

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

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

Delete Folder:os.rmdir() method

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

import os
os.rmdir(“myfolder”)

with open() statement

With the with open() as statement, you get better syntax and exceptions handling.

The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks.

In addition, it will automatically close the file. When you use with statement with open function, you do not need to close the file at the end, because with would automatically close it for you. The with statement provides a way for ensuring that a clean-up is always used.

with open("welcome.txt") as file: # Use file to refer to the file object

   data = file.read()

   do something with data

write

with open('output.txt', 'w') as file:  # Use file to refer to the file object

    file.write('Hi there!')



Continue Learning