0% found this document useful (0 votes)
3 views

file handling - Jupyter Notebook 27-01-2025

The document provides an overview of file handling in Python, detailing operations such as opening, reading, writing, and closing files. It explains different file modes ('r', 'w', 'x', 'a', 't') and demonstrates how to use functions like read(), write(), and close(). Additionally, it covers the use of with...open for automatic file closure and includes examples of error handling in file operations.

Uploaded by

nirajjoshi072003
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

file handling - Jupyter Notebook 27-01-2025

The document provides an overview of file handling in Python, detailing operations such as opening, reading, writing, and closing files. It explains different file modes ('r', 'w', 'x', 'a', 't') and demonstrates how to use functions like read(), write(), and close(). Additionally, it covers the use of with...open for automatic file closure and includes examples of error handling in file operations.

Uploaded by

nirajjoshi072003
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

1/27/25, 11:02 AM file handling - Jupyter Notebook

File Handling
A file is a named location used for storing data. For example, main.py is a file that is always
used to store Python code.

Python provides various functions to perform different file operations, a process known as
File Handling.

There are different file operations in python.

Opening Files

Reading Files

Writing Files

Closing Files

Creating New Files

Opening Files in Python


In Python, we need to open a file first to perform any operations on it—we use the open()
function to do so.

In [3]: 1 file=open("testing.txt") # in read mode ahe file

Different Modes to Open a File in Python


"r" - Read - Default value. Opens a file for reading, error if the file 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

"a" - Append - Opens a file for appending, creates the file if it does not exist

"t" - Text - Default value. Text mode

In [11]: 1 file=open("testing.txt","r")

Reading Files in Python


Python provides several methods to read the content of a file:

read() : Reads the entire file content as a string.

localhost:8888/notebooks/Desktop/NHANU/python/python jupitor/file handling.ipynb# 1/8


1/27/25, 11:02 AM file handling - Jupyter Notebook

In [12]: 1 content=file.read()

In [14]: 1 print(content)

welcome to file handling.


different modes of open file
Opening Files

Reading Files

Writing Files

Closing Files

Creating New Files

In [17]: 1 f=open("try_file.txt","r")

In [19]: 1 print(f.read())

In [21]: 1 f.close()

In [23]: 1 f.read() # try_file.txt is closed therefore can't read

--------------------------------------------------------------------------
-
ValueError Traceback (most recent call las
t)
Input In [23], in <cell line: 1>()
----> 1 f.read()

ValueError: I/O operation on closed file.

In [26]: 1 # to give command from where to read the file


2 ​
3 f=open("try_file.txt","r") # opening the file
4 print(f.tell()) # f.tell ne starting chi position samjate # cursing po

In [33]: 1 print(f.read()) # reading the complete file

In [31]: 1 print(f.tell()) # cursing position after reading the complete file

62

In [34]: 1 f.close() # closeing the file

localhost:8888/notebooks/Desktop/NHANU/python/python jupitor/file handling.ipynb# 2/8


1/27/25, 11:02 AM file handling - Jupyter Notebook

In [36]: 1 f=open("try_file.txt")
2 f.seek(24)
3 print(f.read())

it is high level programming language.

In [38]: 1 print(f.tell())

62

In [40]: 1 f.close()

Reading Files in Python


Python provides several methods to read the content of a file:

read() : Reads the entire file content as a string.

Writing to Files in Python


To write data to a file, it needs to be opened in write ("w") or append ("a") mode:

write() : Writes a string to the file.

If you have opened the file in read mode, then you cannot perform write operation on it.

If you have opened the file in write mode, then you cannot perform read operation on it.

Closing Files in Python


When we are done performing operations on the file, we need to close the file properly. We
use the close() function to close a file in Python.

Opening a Python File Using with...open


In Python, there is a better way to open a file using with...open.

Here, with...open automatically closes the file, so we don't have to use the close()
function.

In [43]: 1 f=open("test.txt","w")
2 f.write("sql is a structured query language. \n It is used for maintain
3 f.close()

In [46]: 1 f=open("test.txt","r")
2 print(f.read())

sql is a structured query language.


It is used for maintaining database

localhost:8888/notebooks/Desktop/NHANU/python/python jupitor/file handling.ipynb# 3/8


1/27/25, 11:02 AM file handling - Jupyter Notebook

In [48]: 1 f.close()

In [51]: 1 f=open("excel.txt","w")
2 f.write("excel is used for creating and maintaing the report. \n Excel
3
4
5 f.close()

In [53]: 1 f=open("excel.txt","r")
2 print(f.read())
3 f.close()

excel is used for creating and maintaing the report.


Excel have a lots of feature for creating report and dashboard

Create a New File


"x" - Create - will create a file, returns an error if the file exist

"a" - Append - will create a file if the specified file does not exist

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

Working with File Pointers - seek() and


tell()
tell() : Returns the current position of the file pointer (in bytes).

In [58]: 1 f=open("text.txt","a")
2 f.write("\n It has 5 command DDL, DML, DQL, TCL, DCL. \n there are some
3 f.close()

In [59]: 1 f=open("text.txt","r")
2 print(f.read())
3 f.close()

It has 5 command DDL, DML, DQL, TCL, DCL.


there are some built in functions in sql
It has 5 command DDL, DML, DQL, TCL, DCL.
there are some built in functions in sql
It has 5 command DDL, DML, DQL, TCL, DCL.
there are some built in functions in sql

In [1]: 1 f=open("powerbi.txt","a")
2 f.write("power bi is visualization tool")
3 f.close()

In [2]: 1 f=open("powerbi.txt","r")
2 print(f.read())

power bi is visualization toolpower bi is visualization toolpower bi is vi


sualization tool

localhost:8888/notebooks/Desktop/NHANU/python/python jupitor/file handling.ipynb# 4/8


1/27/25, 11:02 AM file handling - Jupyter Notebook

In [65]: 1 f=open("excel.txt","x")
2 f.write("hello excel")
3 f.close()

--------------------------------------------------------------------------
-
FileExistsError Traceback (most recent call las
t)
Input In [65], in <cell line: 1>()
----> 1 f=open("excel.txt","x")
2 f.write("hello excel")
3 f.close()

FileExistsError: [Errno 17] File exists: 'excel.txt'

In [68]: 1 f=open("excel2.txt","x")
2 f.write("hello excel")
3 f.close()

In [70]: 1 f=open("excel2.txt","r")
2 print(f.read())

hello excel

In [72]: 1 f.close()

In [75]: 1 # r+ ===> read + write, if a file doesn't exist it will throw error wil
2 ​
3 f=open("text.txt","r+")
4 print(f.read())
5 print("***********************************************")
6 f.write("\n sql has sub topics like sub quries and joins ")
7 ​
8 f.seek(0)
9 print(f.read())
10 f.close()

It has 5 command DDL, DML, DQL, TCL, DCL.


there are some built in functions in sql
It has 5 command DDL, DML, DQL, TCL, DCL.
there are some built in functions in sql
It has 5 command DDL, DML, DQL, TCL, DCL.
there are some built in functions in sql
sql has sub topics like sub quries and joins
sql has sub topics like sub quries and joins
***********************************************

It has 5 command DDL, DML, DQL, TCL, DCL.


there are some built in functions in sql
It has 5 command DDL, DML, DQL, TCL, DCL.
there are some built in functions in sql
It has 5 command DDL, DML, DQL, TCL, DCL.
there are some built in functions in sql
sql has sub topics like sub quries and joins
sql has sub topics like sub quries and joins
sql has sub topics like sub quries and joins

localhost:8888/notebooks/Desktop/NHANU/python/python jupitor/file handling.ipynb# 5/8


1/27/25, 11:02 AM file handling - Jupyter Notebook

In [77]: 1 """" w+ ===> write + read ===> mode will write the data
2 and create a new file if file doesn't exit otherwise replace the data"
3 ​
4 f=open("text.txt","w+")
5 f.write("we are learning the file handling \n we are learning the diff
6 f.seek(0)
7 print(f.read())
8 f.close()
9 ​

we are learning the file handling


we are learning the different modes of file handling

In [80]: 1 """ a+ mode ===> append + read ===> this mode will append the data in
2 and if file doesn't exist it will create a new file and the read the da
3 ​
4 f = open("text.txt","a+")
5 f.write("\n our next topic is oops")
6 f.seek(0)
7 print(f.read())
8 f.close()

we are learning the file handling


we are learning the different modes of file handling
our next topic is oops
our next topic is oops
our next topic is oops

27-01-2025
In [3]: 1 # readline===> for single line
2 # readlines===> for multiple line

In [7]: 1 f=open("text.txt","r")
2 print(f.readline())
3 print(f.readline(10))
4 f.close()

we are learning the file handling

we are le

In [9]: 1 f=open ("text.txt")


2 f.seek(10)
3 print(f.readline())
4 f.close()

rning the file handling

In [11]: 1 f=open("text.txt")
2 print(f.readlines())

['we are learning the file handling \n', ' we are learning the different
modes of file handling \n', ' our next topic is oops\n', ' our next topic
is oops\n', ' our next topic is oops']

localhost:8888/notebooks/Desktop/NHANU/python/python jupitor/file handling.ipynb# 6/8


1/27/25, 11:02 AM file handling - Jupyter Notebook

In [13]: 1 f=open("color.txt","r")
2 s=f.read()
3 l=s.split(" ") # to split a line into individual words
4 print(l)
5 print(len(l))

['black', 'purple', 'white', 'red', 'brown', 'pink', 'yellow', 'orange',


'']
9

exception handling
In [15]: 1 # normally all the error are by default handled by python interpretor
2 ​
3 a=2
4 b=0
5 a/b

--------------------------------------------------------------------------
-
ZeroDivisionError Traceback (most recent call las
t)
Input In [15], in <cell line: 5>()
3 a=2
4 b=0
----> 5 a/b

ZeroDivisionError: division by zero

In [17]: 1 try:
2 a=2
3 b=0
4 print(a/b)
5 except:
6 print("you are dividing int with 0")

you are dividing int with 0

In [20]: 1 num=[2,4,5,6]
2 print(num[0])
3 print(num[11])

--------------------------------------------------------------------------
-
IndexError Traceback (most recent call las
t)
Input In [20], in <cell line: 3>()
1 num=[2,4,5,6]
2 print(num[0])
----> 3 print(num[11])

IndexError: list index out of range

localhost:8888/notebooks/Desktop/NHANU/python/python jupitor/file handling.ipynb# 7/8


1/27/25, 11:02 AM file handling - Jupyter Notebook

In [22]: 1 try:
2 num=[2,4,5,6]
3 print(num[11])
4 except:
5 print("index is missing") # this will work only when there is error
6 else:
7 print("no error") # this will work when there is no error

index is missing

In [24]: 1 try:
2 num=[2,4,5,6]
3 print(num[2])
4 except:
5 print("index is missing")# this will work only when there is error
6 else:
7 print("no error") # this will work when there is no error

5
no error

In [26]: 1 try:
2 num=[2,4,5,6]
3 print(num[3])
4 except:
5 print("index is missing")# this will work only when there is error
6 else:
7 print("no error")# this will work when there is no error

6
no error

In [29]: 1 try:
2 num=[2,4,5,6]
3 print(num[0])
4 except:
5 print("index is missing")# this will work only when there is error
6 else:
7 print("no error")# this will work when there is no error
8 finally:
9 print("successfully completed")

2
no error
successfully completed

In [ ]: 1 ​

localhost:8888/notebooks/Desktop/NHANU/python/python jupitor/file handling.ipynb# 8/8

You might also like