Python Tutorial

Introduction Python Features Python Applications System requirements for Python Python Installation Python Basics Python Variables Python Data Types Python IDE Python Keywords Python Operators Python Comments Python Pass Statement

Python Conditional Statements

Python if Statement Python elif Statement Python If-else statement Python Switch Case

Python Loops

Python for loop Python while loop Python Break Statement Python Continue Statement Python Goto Statement

Python Arrays

Python Array Python Matrix

Python Strings

Python Strings Python Regex

Python Built-in Data Structure

Python Lists Python Tuples Python Lists vs Tuples Python Dictionary Python Sets

Python Functions

Python Function Python min() function Python max() function Python User-define Functions Python Built-in Functions Anonymous/Lambda Function in Python

Python File Handling

Python File Handling Python Read CSV Python Write CSV Python Read Excel Python Write Excel Python Read Text File Python Write Text File Read JSON File in Python

Python Exception Handling

Python Exception Handling Python Errors and exceptions Python Assert

Python OOPs Concept

OOPs Concepts in Python Classes & Objects in Python Inheritance in Python Polymorphism in Python Python Encapsulation Python Constructor Static Variables in Python Abstraction in Python

Python Iterators

Iterators in Python Yield Statement In Python

Python Generators

Python Generator

Python Decorators

Python Decorator

Python Functions and Methods

Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods

Python Modules

Python Modules Python Datetime Module Python Calendar Module  

Python MySQL

Python MySQL Python MySQL Update Operation Python MySQL Delete Operation

Python MongoDB

Python MongoDB

Python Data Structure Implementation

Python Stack Python Queue Python Hash Table Python Graph

Python Advance Topics

Speech Recognition in Python Face Recognition in Python Python Rest API Python Command Line Arguments Python JSON Python Virtual Environment Type Casting in Python Collections in python Python Enumerate Python Debugger Python DefaultDict

Misc

Python PPTX Python Pickle Python Seaborn Python Coroutine Python EOL Python Infinity Python math.cos and math.acos function Python Project Ideas Based On Django Reverse a String in Python Reverse a Number in Python Python Word Tokenizer Python Trigonometric Functions Python try catch exception GUI Calculator in Python Implementing geometric shapes into the game in python Installing Packages in Python Python Try Except Python Sending Email Socket Programming in Python Python CGI Programming Python Data Structures Python abstract class Python Compiler Python K-Means Clustering List Comprehension in Python3 NSE Tools In Python Operator Module In Python Palindrome In Python Permutations in Python Pillow Python introduction and setup Python Functionalities of Pillow Module Python Argmin Python whois Python JSON Schema Python lock Return Statement In Python Reverse a sentence In Python tell() function in Python Why learn Python? Write Dictionary to CSV in Python Write a String in Python Binary Search Visualization using Pygame in Python Latest Project Ideas using Python 2022 Closest Pair of Points in Python ComboBox in Python Python vs R Python Ternary Operators Self in Python Python vs Java Python Modulo Python Packages Python Syntax Python Uses Python Logical Operators Python Multiprocessing Python History Difference between Input() and raw_input() functions in Python Conditional Statements in python Confusion Matrix Visualization Python Python Algorithms Python Modules List Difference between Python 2 and Python 3 Is Python Case Sensitive Method Overloading in Python Python Arithmetic Operators Design patterns in python Assignment Operators in Python Is Python Object Oriented Programming language Division in Python Python exit commands Continue And Pass Statements In Python Colors In Python Convert String Into Int In Python Convert String To Binary In Python Convert Uppercase To Lowercase In Python Convert XML To JSON In Python Converting Set To List In Python Covariance In Python CSV Module In Python Decision Tree In Python Difference Between Yield And Return In Python Dynamic Typing In Python Abstract design pattern in python Builder design pattern in python Prototype design pattern in Python Creational design patterns in Python

How to

How to convert integer to float in Python How to reverse a string in Python How to take input in Python How to install Python in Windows How to install Python in Ubuntu How to install PIP in Python How to call a function in Python How to download Python How to comment multiple lines in Python How to create a file in Python How to create a list in Python How to declare array in Python How to clear screen in Python How to convert string to list in Python How to take multiple inputs in Python How to write a program in Python How to compare two strings in Python How to create a dictionary in Python How to create an array in Python How to update Python How to compare two lists in Python How to concatenate two strings in Python How to print pattern in Python How to check data type in python How to slice a list in python How to implement classifiers in Python How To Print Colored Text in Python How to develop a game in python How to print in same line in python How to create a class in python How to find square root in python How to import numy in python How to import pandas in python How to uninstall python How to upgrade PIP in python How to append a string in python How to open a file in python

Sorting

Python Sort List Sort Dictionary in Python Python sort() function Python Bubble Sort

Programs

Factorial Program in Python Prime Number Program in Python Fibonacci Series Program in Python Leap Year Program in Python Palindrome Program in Python Check Palindrome In Python Calculator Program in Python Armstrong Number Program in Python Python Program to add two numbers Anagram Program in Python Even Odd Program in Python GCD Program in Python Python Exit Program Python Program to check Leap Year Operator Overloading in Python Pointers in Python Python Not Equal Operator Raise Exception in Python Salary of Python Developers in India What is a Script in Python Singleton design pattern in python

Python File Handling

What is the file?

The file is a collection of data in a single unit. It is used to store information in the non-volatile memory such as hard-disk.

Computer programs generally run on the RAM (Random Access Memory) which is a volatile memory. After termination of the program, all data gets lost, so we need to store data into permanent storage or local file.

Hence, in Python, the file handling can be done by the following order:

  • Open a file
  • Read or write (perform operation)
  • Close the file

Open a file

Python provides a built-in function open () which is used to open a file. This function will return a file object. The open () is used along with the two arguments  to return file object. The first argument accepts file name, and the second accepts the file mode. The syntax is the following:

fs = open (filename, access mode)

filename- This argument contains the name of the file which we want to open.

access_mode - This argument determines the mode in which file to be open such as read, write, append, etc. This argument is not mandatory, the file will open in r read mode by default if this argument is not passed.

Here is a table of different file modes of opening files:

Mode Description
r This mode opens a file in read-only mode. The file pointer is positioned at the beginning of the file.
w This mode opens a file in write mode. If the file does not exist, creates a new file.
a This mode opens a file for appending. The file pointer is positioned at the end of the file. If a file does not exist, then it creates a new file in write mode.
rb This opens a file for read in binary mode.
wb This opens a file for write in binary mode. If the file does not exist, creates a new file.
ab This opens a file for append in binary format. The file pointer is at the end of the file if the file exists. If the file does not exist, it creates a new file for writing.
r+ This opens a file in both reading and writing.
w+ This opens a file in both write and reading
a+ This opens a file in both appending and reading
rb+ This opens a file for both reading and writing in binary format. The file pointer is located at the beginning of the file.
wb+ This opens a file for both writing and reading in binary format. The file pointer is located at the beginning of the file.
ab+ This opens a file for both appending and writing in binary format. The file pointer is located at the beginning of the file.

Let’s consider the following example:

fs = open('newfile.txt','w')

if fs:
    print('file opened successfully')

Output:

file opened successfully

Closing a file

We need to close a file properly after completion of the file operation. Python provides a close () method to close a file. The close () function free up the resources that were tied with the file. Python provides the garbage collector to clean, but it is good practice to use close () to close the file properly.

fs = open('myfile.txt','w')
#perform file operation
fs.close()

Sometimes we forget to close a file, it may cause an error.  The best way to close a file is by using the with statement.          

with open('myfile.txt','w'):

    # perform file operation

The with statement will close the file internally. We don’t need to call it explicitly.

How to write into file

Python provides write () which is used to write into the file. We need to open it in write ‘w’ or ‘a’ mode. Consider the following example:

# open the myfile.txt in write mode. Creates a new file if no such file exists.
fs = open('myfile.txt','w')
#writing the content to the file
fs.write("We are writing this line into the file")
fs.write("Python is the most popular programming language")
#closing the opened file   
fs.close() 

myfile.txt

We are writing this line into the file. Python is the most popular programming language.

How to read the file

Python provides read () to read file content. The read () method reads a string from the file. The syntax is the following:

Fileobj.read(count)

The count argument accepts the positive number and counts the string. For example:

fs = open('myfile.txt','r')
z=fs.read(10)
y = type(z)
print(z)

Output:

We are wri

Python provides a readline () function that read the file line by line. It reads a file till the newline.

fs = open('myfile.txt','r+')
z = fs.readline()
print(z)

Output:

Hi, there i am the best Hi, there i am the best

There is another method readlines () which returns a list of the lines of the entire file. This returns empty value when end of file is reached. You can execute both methods and observe the difference.

fs = open ('myfile.txt','r+')
z = fs.readlines()
print(z)

Output:

['Hi, there i am the best Hi, there i am the best ']

Creating a new file

The following access mode is used with open () to create a new file with the specified name.

x – It is used to create a new file with a specified name. If the file exists with the same name, then it will show an error.

a – It appends the file content if the file already exists. It will create a new file if no such file exists.

w- It creates new file with specified name if no such file exists. If the file exists, then it will overwrite the file content.

Example-1

fs = open('myname.txt','x')
print(fs) # returns the file object

if fs:
    print("File created
successfully")

Output:

<_io.TextIOWrapper name='myname.txt' mode='x' encoding='cp1252'>
 File created successfully 

File Pointer Positions

The tell() method allows us to know the current position of pointer within the file; which means , the next read or write will occur at that many bytes from the beginning of the file.

fs = open("myfile.txt", "r")
# initially the filepointer is at 0
print("The file pointer is at byte :", fs.tell())
# reading the content of the file
content = fs.read()
# after the read operation file pointer modifies. tell() returns the location of the fileptr.
print("After reading, the file pointer is at:", fs.tell())

Output:

The file pointer is at byte : 0
After reading, the file pointer is at: 48 

Modification in the pointer position

Python provides the seek (offset [, from]) method to perform modification in the current file position. It consists of two arguments which are the following.

offset  -  It indicates the number of bytes to be moved.

from -  It specifies the reference position from where the bytes are to be moved.

Note -  The from is set to 0, it means use the beginning of the file as the reference position. If it is set to 1 which means use the current position as the reference position and if it is set to 2 then the end of the file is used as the reference position.

fs = open("myfile.txt", "r")
# initially the filepointer is at 0
print("The
file pointer is at byte :", fs.tell())
#Modification on the cursor position
print("Changing
the pointer position:",fs.seek(10))
# after the read operation file pointer modifies. tell() returns
the location of the fileptr.
print("After
reading, the file pointer is at:", fs.tell())

Output:

The file pointer is at byte : 0
Changing the pointer position: 10
After reading, the file pointer is at: 10 

Python os module

The os module provides various functions for interacting with the operating system such as renaming, deleting, etc.

Some of the module functions are the following:

  • Renaming the file

The rename () function is used to rename the specified file to a new name. The syntax is given below.

rename(src,dst)

src- Current file name

dst- New file name

Example-1

import os
#Renaming the file myfile to newfile
os.rename('myfile.txt','newfile.txt')
  • Removing the file

The remove () function is used to remove the specified file. The syntax is given below

remove(filename)

Example-2

import os
#Removing a file
os.remove('newfile')
  • Creating a new directory

The os module provides mkdir () function, which is used to create the directories in the current directory.  The syntax is given below:

mkdir (directory_name) 

Example-3

import os;    
 #creating a new directory with the new name  
 os.mkdir("new_directrory")   
  • Changing the current working directory

The chdir () method is used to change the current working directory to a specified directory. The syntax is given below:

chdir(“new_dir”)
  • The getcwd() function

It displays the current working directory.

getcwd()

Example-4

import os

 # Changing a directory to "/home/newdir"
 os.chdir("/User/newdir")
  • Remove the Directrory

The os module provides rmdir () function to remove a directory which is passed as an argument.

rmdir(‘dirname’)

Example-5

import os

# This would remove "/tmp/test"  directory.
os.rmdir("/home/newdir”)

The file related function

There are various file functions which are given below.

Sr. Function Description
1 File.open() It is used to open a file and return file object
2 File.close() It is used to close the opened file. Once a file closed, can’t be read and write.
3 File.read() It is used to read a file.
4 File.seek(offset[,from) It is used to modify the file pointer position.
5 File.tell() It returns the current position of the pointer
6 File.readline([size]) It reads lines from the file
7 File.readlines(sizehint) It returns a list containing all lines of the file.
8 File.readable() It returns the Boolean True if the file is readable.
9 File.writable() It returns the Boolean True if the file is writable.
10 File.seekable It returns the Boolean True if the file is seekable.
11 File.flush() It flushes the internal buffer.
12 File.next() It returns the next line from the file.
13 File.write(str) It is used to write specified string to the file.



ADVERTISEMENT
ADVERTISEMENT