AlphaCodingSkills

Python - File Handling


Advertisements

Previous Page Next Page

File-handling is an essential part of programming. Python has several functions for file handling such as creating, opening, reading, updating and deleting files.

Open File

The Python open() function is used to open a file and returns it as a file object. It takes two parameters - filename and mode. Please see the syntax below:

Syntax


open(filename, mode)

Parameters

filename Required. specify filename with path which need to be opened.
mode Optional. specify mode of opening the file. default is read mode for text file that is "rt".

The different modes of opening a file are mentioned below:

ModeDescription
rDefault value. Opens a file for reading only. Raise an exception if the file does not exist.
r+Opens a file for reading and writing. Raise an exception if the file does not exist.
wOpens a file for writing only. Creates the file if it does not exist.
w+Opens a file for reading and writing. Creates the file if it does not exist.
aOpens a file for appending only. Creates the file if it does not exist.
a+Opens a file for appending and reading. Creates the file if it does not exist.
xCreates the specified file. Raise an exception if the file already exists.
x+Creates the specified file and Opens the file in reading and writing mode. Raise an exception if the file already exists.

Apart from this, the file can be handled as binary or text mode

ModeDescription
tDefault value. Opens a file in the text mode.
bOpens a file in the binary mode.

In the below example, open() function is used to open the file called python_test.txt in "rt" mode which means read text mode. The "rt" mode is also the default mode hence it does not require to specify.

MyFile = open("python_test.txt", "rt")

# is equivalent to
MyFile = open("python_test.txt")

Read File

The open() function returns a file object which has read() method to read the content of the file object. In the below example, read() method is used to read the whole content of the file called MyFile.

MyFile = open("python_test.txt", "r")
print(MyFile.read())

Output

Python is a programming language.
Learning Python is fun.

Read a part of file

The Python read() method has an optional parameter which is used to specify number of bytes to read and return of the file object. In the below example, read() method is used to read the partial content of the file called MyFile.

MyFile = open("python_test.txt", "r")
#read first 33 bytes of the content
print(MyFile.read(33))

#read next 10 bytes of the content
print(MyFile.read(10))

Output

Python is a programming language.

Learning

Read Lines

The Python file object has readline() method which is used to read and return one line of the file. If the method is called multiple times, it will read and return multiple lines of the file. In the below example, readline() method is used twice to read first two lines of the file called MyFile.

MyFile = open("python_test.txt", "r")
#read first line of the content
print(MyFile.readline())

#read second line of the content
print(MyFile.readline())

Output

Python is a programming language.

Learning Python is fun.

Loop through the lines of the File

By using for loop, the whole content of the file can be read line by line.

MyFile = open("python_test.txt", "r")

for line in MyFile:
  print(line)

Output

Python is a programming language.

Learning Python is fun.

Similarly, the while loop can also be used to read the whole content of the file line by line.

MyFile = open("python_test.txt", "r")

line = MyFile.readline()
while line:
  print(line)
  line = MyFile.readline()

Output

Python is a programming language.

Learning Python is fun.

Close File

The Python file object has close() method which is used to close the specified open file. In the below example, Python file close() method is used to close an opened file called MyFile.

MyFile = open("python_test.txt", "r")

#read content before closing the file
print(MyFile.read())
MyFile.close()

#read content after closing the file
print(MyFile.read())

Output

Python is a programming language.
Learning Python is fun.

ValueError: I/O operation on closed file.

Write to an Existing File

The Python file object has write() method which is used to write content in the specified open file. To write content in the file, two file open() modes can be used.

  • "a" - append mode. to append to the end of the file.
  • "w" - write mode. to overwrite any existing content of the file.

The below example explains how to write content in a given file in append and write mode.

#append content to the file 
MyFile = open("python_test.txt", "a")
MyFile.write("add more content.")
MyFile.close()

#overwrite existing content of the file 
MyFile = open("python_test.txt", "w")
MyFile.write("add more content.")
MyFile.close()

Create a New File

To create a new file, the file open() function can be used in following modes:

  • "a" - append mode. Opens a file in append mode and creates the file if it does not exist.
  • "w" - write mode. Opens a file in write mode and creates the file if it does not exist.
  • "x" - create mode. Creates a file and raises exception if it already exists.

The below example explains how to create a new file called NewFile if it does not exist using append, write and create mode.

#Creates a file "MyFile" if it does not exist 
MyFile = open("python_test.txt", "a")

#Creates a file "MyFile" if it does not exist 
MyFile = open("python_test.txt", "w")

#Creates a file "MyFile" if it does not exist  
MyFile = open("python_test.txt", "x")

Delete a File

To delete a file, os module must be imported in the current session. The os module contains remove() function which is used for deleting the specified file. In the below example, os.remove() function is used to delete the file called MyFile.

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

Check if File exist

To check whether a file exists or not, the os module contains path.exists() function which can be used to check it.

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

Delete Folder

The os module contains rmdir() function which can be used to delete an entire folder.

import os
os.rmdir("myfolder")

File Handling Methods
MethodsDescription
close() Closes the file
detach() Returns the separated raw stream from the buffer
fileno() Returns a number that represents the stream, from the operating systems perspective
flush() Flushes the internal buffer
isatty() Returns whether the file stream is interactive or not
read() Returns the file content
readable() Returns whether the file stream can be read or not
readline() Returns one line from the file
readlines() Returns a list of lines from the file
seek() Change the file position
seekable() Returns whether the file allows us to change the file position
tell() Returns the current file position
truncate() Resizes the file to a specified size
writable() Returns whether the file can be written to or not
write() Writes the specified string to the file
writelines() Writes a list of strings to the file

Previous Page Next Page