Python File Handling

by Apr 1, 2020Python

In this article, we will discuss all about file handling in Python. Let us have a quick look at the contents shown below:

Introduction

A file is a collection of data stored on a secondary storage device like a hard disk. Files are non-volatile storage media.


File open

The function to open a file in Python is open() function and it takes two parameters. One is filename and another is mode. The methods to open a file are:

  • ” r “: Open a file for reading. But error occurs if the file doesn’t exist.
  • “a “: Open a file for appending and create a file if it doesn’t exist.
  • “w”: Open a file for writing and creates a file if doesn’t exist.
  • ” x “: Creates a specified file. But returns error if not there.
  • ” t”: It’s a default value for text mode.
  • ” b”: it’s for binary mode.

Syntax

file= open("myfile.txt", "rb")
print(file) #file name and access modeare specified here

If the file doesn’t exist you will get an error.


Read files

In order to read the content of the files, we can use the read() method.

file=open("myfile.txt","r")
print(f.open())

Parts of a file to read

We also can read a part of a file we want to. The number of characters should be mentioned in this case.

file=open("myfile.txt","r")
print(f.open(5)) #returns Hello(the required word)

Read Lines

The method readline() returns a line in Python.

file=open("myfile.txt","r")
print(f.readline()) 
print(f.readline()) #two readline() methods are used for reading two lines 

Loop

Loop through the lines can print the whole file.

file = open("myfile.txt", "r")
for x in file:
  print(x)

Close files

This method closes the file object. Once a file object is closed you can;t further read from or write into the file object.

file= open("myfile.txt","wb")
print("Name of the file : ",file.name)
print("File is closed . ",file.closed)
print("File is now being closed... You cannot use the file object ")
file.close()
print("File is closed ",file.close())
print(file.read())

Output of the above code will generate an error.

Name of the file : myfile.txt
File is closed . False
File is now being closed... You cannot use the file object
File is closed . True
Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\file.py",line 7, in <module>
     print(file.read())
valueError: I/O operation on closed file

Write a file

Te write() method is used to write a string to an already opened file. This method does not add a newline character (‘\n’) to the end of the string.

file= open("myfile.txt", "w")
file.write("Python is interesting")
file.close()
print("Data written into the file") #returns Data written into the file

Append()

To append a file, one must open it using ‘a’ or ‘ab’ mode depending on whether it is a text file or a binary file.

file= open("myfile.txt", "a")
file.write("\n Python is interesting")
file.close()
print("Data appened to file.........") #returns Data appened to file.........

Splitting words

Python allows you to read lines from a file and splits the line based on a character. By default, this character is space but you can even specify any other character to split words in the string.

with open("myfile.txt", "r") as file:
    line = myfile.readline()
    words=line.split()
    print(words)

Create a New File

To create a new file Python use open() method along with three modes of operations.

  • “x”:Create
  • “a”:Append
  • “w”: Write

The above three modes will generate an error if no file exists.


seek() method

This method is used in case of a read or write at a specific position. This method takes two parameters. One is offset value and another is the from. The from parameter takes three kind of values. Those are:

  • 0 for offset calculated from the beginning.
  • 1 for offset calculated from the current position and
  • 2 for offset calculated from the end.

The syntax: file.seek(offset, from)

We are assuming that the file myfile.txt contains “Python Tutorial” and the following is the code.

file=open("myfile.txt","r+")
file.seek(7,0)
lines=file.readlines()
for i in lines:
    print(i)
file.close()

Rename file

The rename() method takes two arguments the current filename and new filename.

Syntax: os.rename(old_file_name, new_file_name)

See here we use the os module. This module in Python has various methods that can be used to perform file processing operations like renaming and deleting files. To know more you can refer to this site.

import os
os.rename("myfile.txt", "PythonTutorial.txt")
print("File Renamed")

Remove file

This method remove files. This method takes a filename as an argument and delete that file.

syntax: os.remove(file_name)

import os
os.remove("myfile.txt")
print("File Deleted") #returns File Deleted

Directory Methods

Python has various methods in the os module that help programmers to work with directories. This methods allow users to create, remove, and change directories.

mkdir() method is used to create a new directory in the current path.

import os
os.mkdir("New Dir")
print("Directory Created") #returns Directory Created

chdir() method is used to change the current directory.

import os
print("Current working directory is : ",os.getcwd()) #display current working directory
os.chdir("New")
print("The current directory is now....",end = ' ')
print(os.getcwd())

rmdir() method is used to remove or delete directory

import os
os.rmdir("New")
print("Directory Deleted........")#returns Directory deleted

Creating a multiplication Skill in Alexa using python

Written By Itika Sarkar

Hey, this is Itika Sarkar. I'm currently pursuing BTech degree in Electronics & Communication Engineering(2nd year). Writing technical articles, tutorial and innovative projects on modern industry-related technologies are my hobbies.

RELATED POSTS

Python Regular Expression

Python Regular Expression

Python is a general-purpose high-level programming language. Python is mainly used as a support language to software developers. It helps in building control and management and also in testing. The syntax python uses is very simple and similar to the English language....

Introduction to MicroPython and ESP8266

Introduction to MicroPython and ESP8266

For ages, C and C++ have ruled over the embedded system industry. Fast prototyping is an important aspect of the industry today. In fact MicroPython is the best suited for fast prototyping. Students and engineers are becoming very familiar with the Python programming...

Five Best Python Projects for Beginners

Five Best Python Projects for Beginners

Learning and practicing of any programming language can be monotonous. Also, only learning can not be the perfect gain of knowledge if we don't put it into some implementation. Likewise, Python programming language can be interesting but until we don't use it in some...

How to convert .py into .pyc? Compilation of Python Code

How to convert .py into .pyc? Compilation of Python Code

In this article we will see what is a pyc file ,how is it formed,how to convert and compile a pyc file. When we run a code in python it actually goes through a couple of steps before our program reaches the virtual machine It is compiled to bytecode.Then it is...

How to create and install a Python Package?

How to create and install a Python Package?

Requirements Check the tools pip --version pip install wheel What is Python Package Index? What is Distutils? Creating a Package Directory Structure some_root_dir/ |-- README |-- setup.py |-- an_example_pypi_project | |-- __init__.py | |-- useful_1.py | |--...

Docker for beginners tutorial:

Docker for beginners tutorial:

What is Docker? Docker, in simple words is a tool that allows developers who build applications, to package them with all their dependencies into a ‘container’ which can easily be shipped to run on the host operating . Containers do not have high overhead and allow...

Object-Oriented Programming in Python

Object-Oriented Programming in Python

Python Classes and Methods Python is an object-oriented programming language. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made....

Python Flask Tutorial

Python Flask Tutorial

Flask is a web framework that provides libraries to build lightweight web applications in python. It is developed by Armin Ronacher who leads an international group of Python enthusiasts (POCCO). Contents What is Flask? Flask Environment Setup First Flask...

Python Numbers

Python Numbers

In this article you will learn about types of numbers in python and their mathematical operations. So these are the contents of this article : Introduction Decimal Need of DecimalFractionsMathematics Introduction Python supports integer, floating-point number and...

Python Lambda

Python Lambda

In this article, we will discuss on Python lambda. Let us have a quick look on the following contents shown below: IntroductionAdd two numbers using LambdaSum of 10 natural numbersMultiplicationSmaller of two numbers Introduction Lambda functions are the anonymous...

Python Functions

Python Functions

In this article, we will tell about Python functions. We should also know about function defining function calling and variable arguments. Let's have a quick look on the below contents : IntroductionFunction CreationDefinitionDeclarationCallArgumentsRequired...

Python While loop

Python While loop

In this article, we are going to focus on while loops used in python with suitable examples. The content of this article is shown below: IntroductionThe break statementContinue in whileElse in while loop Introduction While loop in Python is a primitive type of...

VIDEOS – FOLLOW US ON YOUTUBE

EXPLORE OUR IOT PROJECTS

IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

Gardening is always a very calming pastime. However, our gardens' plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article,...

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

All you need to know about integrating NodeMCU with Ubidots over MQTT

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

All you need to know about integrating NodeMCU with Ubidots over Https

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

Sending Temperature data to ThingSpeak Cloud and Visualize

In this article, we are going to learn “How to send temperature data to ThingSpeak Cloud?”. We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in the world. But "What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows...

Amaze your friend with latest tricks of Raspberry Pi and Firebase

Introduction to our Raspberry Pi and Firebase trick Let me introduce you to the latest trick of Raspberry Pi and Firebase we'll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit...

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....