0% found this document useful (0 votes)
32 views8 pages

Unit - III

Uploaded by

xyzx010101
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views8 pages

Unit - III

Uploaded by

xyzx010101
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Python Programming

Unit - IV

UNIT III
FILE HANDLING
 Python File Input-Output:
 File input-output in Python is the process of reading from and writing to files on your computer's
storage. This is essential for handling data persistence and manipulation. Here are the basic steps:
1. Opening a File:
 Use the open() function to open a file.
 To perform any operation on a file, you first need to open it using the open() function.
 Syntax:
file_object = open(file_path, mode).

i. file_path:
 refers to the location or path of the file on your computer's filesystem. It includes the directory
or folder where the file is located, along with the file's name and extension. For example, in
the path "D:\Programs\Python\example.txt",
 D:\Programs\Python\ is the directory and example.txt is a file
ii. mode:
 in file handling specifies the purpose for which a file is opened. There are different modes
like:
1. 'r' (Read):
 This mode allows only reading from the file.
 If the file does not exist, it raises a FileNotFoundError.
 It is the default mode when opening a file.

file = open('example.txt', 'r')

2. 'w' (Write):
 This mode allows writing to the file. If the file exists, it will overwrite (i.e., erase all data)
and start writing from the beginning.
 If the file does not exist, it will create a new one.

file = open('example.txt', 'w')

3. 'a' (Append):
 This mode allows appending data to the end of the file.

Page 1 of 8
By, Mritunjay Kr. Ranjan
Python Programming
Unit - IV

 If the file exists, it will not overwrite and start writing from the end.
 If the file does not exist, it will create a new one.

file = open('example.txt', 'a')

4. 'r+' (Read and Write):


 This mode allows both reading and writing to the file.
 It does not overwrite the file.
 If the file does not exist, it raises a FileNotFoundError.

file = open('example.txt', 'r+')

5. 'w+' (Write and Read):


 This mode allows both reading and writing to the file.
 If the file exists, it will overwrite and start writing from the beginning.
 If the file does not exist, it will create a new one.

file = open('example.txt', 'w+')

6. 'a+' (Append and Read):


 This mode allows both appending and reading.
 It does not overwrite the file.
 If the file does not exist, it will create a new one.

file = open('example.txt', 'a+')

2. Writing to a File:
i. Open the File:
 Use the open() function to open the file in the desired mode
 (in this case, "w" for write).

file = open('example.txt', 'w')

ii. Write Content:


 Use the write() method to write data to the file.
file.write("Hello, World!")

 The writelines() method writes the items of a list to the file.

Page 2 of 8
By, Mritunjay Kr. Ranjan
Python Programming
Unit - IV

Where the texts will be inserted depends on the file mode and stream position.

iii. Close the File:


 It's crucial to close the file after writing to free up system resources.

file.close()

3. Reading from a File:


 For reading, use methods like read() , readline() ,or readlines()
 depending on whether you want to read the entire file, one line at a time, or all lines into a list.
i. read():
 read() is used to read the entire content of the file as a string.

content = file.read()

ii. readline():
 readline() is used to read a single line from the file.

line = file.readline()

iii. readlines():
 readlines() is used to read all lines of the file into a list where each line is an element of
the list.

lines = file.readlines()

4. Closing a File:
 It's important to close a file after you're done with it to free up system resources.
 Use the close() method.
 Program

# Opening a File in Write Mode

#When you have file in the same directory your python


program is placed then only pass the name of that file

Page 3 of 8
By, Mritunjay Kr. Ranjan
Python Programming
Unit - IV

#else provide the complete path of your file


file = open('example.txt', 'w')

# Writing Content to the File


file.write("Hello, World!\n")
file.write("This is line 2.\n")
file.write("And this is line 3.\n")

# Closing the File


file.close()

# Opening the File in Read Mode


file = open('example.txt', 'r')

# Reading the Entire Content


content = file.read()
print("Content of the file:")
print(content)

# Closing the File


file.close()

# Opening the File in Read Mode


file = open('example.txt', 'r')

# Reading One Line at a Time


line1 = file.readline()
line2 = file.readline()

print("\nLines read one at a time:")


print(line1, end='')
print(line2, end='')

Page 4 of 8
By, Mritunjay Kr. Ranjan
Python Programming
Unit - IV

# Closing the File


file.close()

# Opening the File in


 Output
Read Mode
file =
Content of the file:
open('example.txt',
Hello, World!
'r')
This is line 2.
And this is line 3.
# Reading All Lines
into a List
lines =
Lines read one at a time:
file.readlines()
Hello, World!
This is line 2.
print("\nLines read
into a list:")
Lines read into a list:
print(lines)
['Hello, World!\n', 'This is
line 2.\n', 'And this is line
# Closing the File
3.\n']
file.close()

Example of writelines():

Binary File Handling

Page 5 of 8
By, Mritunjay Kr. Ranjan
Python Programming
Unit - IV

In this file format, the data is stored in the binary format (1 or 0). The binary file doesn't have any terminator
for a newline. Python takes the three required steps to read or write a text file.

 Open a file
 Read or Write file
 Close file

Working with csv files in Python


Python is one of the important fields for data scientists and many programmers to handle a variety of
data. CSV (Comma-Separated Values) is one of the prevalent and accessible file formats for storing and
exchanging tabular data.
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet
or database. A CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data
record. Each record consists of one or more fields, separated by commas. The use of the comma as a
field separator is the source of the name for this file format. For working CSV files in Python, there is
an inbuilt module called CSV.

Page 6 of 8
By, Mritunjay Kr. Ranjan
Python Programming
Unit - IV

Reading/ writing into csv file:

seek() method
In Python, seek() function is used to change the position of the File Handle to a given specific
position. File handle is like a cursor, which defines from where the data has to be read or written in
the file.

Syntax: f.seek(offset, from_what), where f is file pointer


Parameters:
Offset: Number of positions to move forward
from_what: It defines point of reference.
Returns: Return the new absolute position.
The reference point is selected by the from_what argument. It accepts three values:

0: sets the reference point at the beginning of the file

1: sets the reference point at the current file position

2: sets the reference point at the end of the file

By default from_what argument is set to 0.

Page 7 of 8
By, Mritunjay Kr. Ranjan
Python Programming
Unit - IV

Python File tell() Method

The tell() method returns the current file position in a file stream.
file.tell()
Example:
f = open("demofile.txt", "r") Output:
Hello! Welcome to demofile.txt
print(f.readline()) 32
print(f.tell())

******

Page 8 of 8
By, Mritunjay Kr. Ranjan

You might also like