0% found this document useful (0 votes)
19 views44 pages

Python File Operations Guide

Unit 4 of the document covers Python file operations, detailing how to read, write, and manipulate files using various modes (e.g., read, write, append). It explains the use of the open() function, file modes, and methods for reading and writing data, including examples for each operation. The document emphasizes the importance of proper file handling and introduces the 'with' statement for automatic file closure.

Uploaded by

ayushthegreat81
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)
19 views44 pages

Python File Operations Guide

Unit 4 of the document covers Python file operations, detailing how to read, write, and manipulate files using various modes (e.g., read, write, append). It explains the use of the open() function, file modes, and methods for reading and writing data, including examples for each operation. The document emphasizes the importance of proper file handling and introduces the 'with' statement for automatic file closure.

Uploaded by

ayushthegreat81
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

FUNDAMENTALS OF

PYTHON
PROGRAMMING
FOR BEGINNERS
UNIT-4
PYTHON FILE OPERATIONS

Mr. Rahul Kumar Gupta Dr. Arun Kumar. G


Assistant Professor Professor & HOD
Department of Electronics & Communication Engg.
JSS Academy of Technical Education , Noida, UP.
Python File Operations

UNIT
4
Python File Operations

UNIT-4: Python File Operations: Reading files, writing files in python, Understanding
read functions, read (), readline (), readlines (). Understanding write functions, write ()
and writelines () Manipulating file pointer using seek Programming, using file operations.

4.1 INTRODUCTION TO PYTHON FILE OPERATIONS:


In Python, file operations allow programs to create, read, write, and modify data stored
in files. File handling is essential for storing information permanently, since data stored
in variables is lost when the program ends.
The built-in open() function is used to work with files. Once opened, we can read/write
data, and finally close the file to release resources.
Python supports two types of files:
• Text files: Store characters in human-readable format. (e.g., .txt)
• Binary files: Store raw bytes. (e.g., .bin, images, audio)

Basic File Handling Process:


1. Open the file using open()
2. Perform the required operation (read / write / append).
3. Close the file using close() (or use with statement to auto-close).

Figure 4.1: Python File Operations

Fundamentals of Python Programming for Beginners 194


Python File Operations
4.2 BASIC FILE OPERATIONS:
File Modes in Python
• File modes in Python tell the program how a file should be opened and what
kind of operation can be performed on it such as reading, writing, or appending
data.
• When we open a file using the open() function, we specify the mode as a string
argument.

Types of File Modes in Python:


Creates
Mode Operation Type Description
File?
'r' Read Opens file for reading only (file must exist). No
'w' Write Opens file for writing. Overwrites file if it exists. Yes
'a' Append Opens file for appending new data to the end. Yes
'x' Create Creates a new file. Gives error if file already exists. Yes
'r+' Read & Write Opens file for both reading and writing. No
'w+' Write & Read Overwrites existing file or creates new one. Yes
'a+' Append & Read Opens file for reading and appending data. Yes
'b' Binary Used for binary files (images, videos, etc.). -
't' Text Default mode for text files. -
'rb' Read (Binary) Opens an existing binary file for reading. No
Opens a file for writing in binary mode (overwrites
'wb' Write (Binary) Yes
if it exists).
Opens a binary file for appending data at the end.
'ab' Append (Binary) Yes
Creates file if it doesn’t exist.

1. Read Mode ('r'):


Used when you only want to read data from a file.
Example Program:
If [Link] file already contains: Hello Rahul
file = open("[Link]", "r")
print([Link]())
[Link]()
The file content of [Link] contains after running the program: Hello Rahul
Note: File must already exist, otherwise an error occurs.

2. Write Mode ('w'):


Used to create a new file or overwrite an existing one.
Example Program:
If [Link] file already contains: XXXXXX
file = open("[Link]", "w")
[Link]("Hello Rahul")
[Link]()
The file content of [Link] contains after running the program: Hello Rahul
Note: Existing content is erased.

3. Append Mode ('a'):


Used to add new data at the end of an existing file.
Example Program:
If [Link] file already contains: Hi
Fundamentals of Python Programming for Beginners 195
Python File Operations
file = open("[Link]", "a")
[Link]("\nHello Rahul")
[Link]()
The file content of [Link] contains after running the program:
Hi
Hello Rahul
Note: Existing content is not erased.

4. Create Mode ('x'):


Used to create a new file. Gives an error if the file already exists.
Example Program:
If [Link] file already contains: Hi
file = open("[Link]", "x")
[Link]("Hello Rahul")
[Link]()
The file content of [Link] contains after running the program, file becomes:
FileExistsError
Note:
• If file already exists → FileExistsError.
• 'x' mode fails if the file already exists.

5. Read + Write Mode ('r+'):


Used to both read and write data in the same file.
Example Program:
If [Link] file already contains: Hello Rahul
file = open("[Link]", "r+")
print("Before:", [Link]())
[Link]("\nHello Rahul")
[Link]()
Note: File must already exist.
(Assuming [Link] initially contains Hello Rahul.)

6. Write + Read Mode ('w+'):


Used to write and then read a file. It overwrites the existing file.

Example Program:
If [Link] file already contains: Hello Rahul
file = open("[Link]", "w+")
[Link]("Hello Rahul")
[Link](0)
print([Link]())
[Link]()
Output:
Hello Rahul
Note: seek(0) moves the file pointer to the beginning for reading.

7. Append + Read Mode ('a+'):


Used to append data and read from the same file.
Example Program:
file = open("[Link]", "a+")
[Link]("\nHello Rahul")
Fundamentals of Python Programming for Beginners 196
Python File Operations
[Link](0)
print([Link]())
[Link]()
(Result in file will include one more “Hello Rahul” at the end.)

8. Binary Modes ('rb', 'wb'):


(Used for binary files like images, videos, or audio files.
Example Program:
# Write bytes
with open("[Link]", "wb") as f:
[Link](b"Hello Rahul")

# Read bytes
with open("[Link]", "rb") as f:
data = [Link]()
print(data)
Output:
b'Hello Rahul'
Note: Binary modes handle raw bytes. Typically used for images or media files.

9. Using with (Recommended Method):


Automatically closes the file after the block finishes.
Example Program:
with open("[Link]", "w") as f:
[Link]("Hello Rahul")
The file closes automatically after the block finishes.

Example: Using with open() (auto-close)


# with automatically closes the file when the block ends
with open("[Link]", "w") as f:
[Link]("This file auto closes")
Output:
(file now contains This file auto closes)
Explanation: Automatically closes the file after use. No explicit close() is required.

10. Append (Binary) Mode ('ab'):


Used to add binary data to the end of an existing binary file (e.g., images, audio, or
binary logs). If the file doesn’t exist, Python automatically creates it.
Example: Using with ab mode
# Open a binary file in append mode and write bytes
with open("binary_data.bin", "ab") as f:
[Link](b"New binary data\n")

# Read back to verify appended content


with open("binary_data.bin", "rb") as f:
data = [Link]()
print(data)
Output:
b'New binary data\n'

Fundamentals of Python Programming for Beginners 197


Python File Operations
Note: (If the file already had previous binary content, this data will appear appended at the
end.)
Explanation:
• 'ab' opens the file for appending binary data.
• If the file doesn’t exist, it is created automatically.
• Data is written as bytes (b"..."), not text strings.
• This mode is useful for logging sensor data, appending binary packets, or adding
metadata to images or media files.

Difference between open( ) and with open( )


Sl.
Using Open( ) Using with open( )
No.
1 • The open() function is used to open • The with open() statement
a file and returns a file object. automatically handles opening and
• You must manually close the file closing the file.
using [Link]() after completing • Even if an error occurs, Python
the operations. automatically closes the file after
• If you forget to close it, it can lead to exiting the block.
memory leaks or file corruption. • It is the recommended and safer
way to handle files.
2 Syntax: Syntax:
file_object = open("filename", "mode") with open("filename", "mode") as file_object:
# Perform file operations # Perform file operations inside this block
file_object.close()
3 Example: Example:
f = open("[Link]", "r") with open("[Link]", "r") as f:
content = [Link]() content = [Link]()
print(content) print(content)
[Link]() # File automatically closed here

4.3 READING FILES IN PYTHON:


Reading a file means accessing its content.

Read Methods in Python


Method Description
read() Reads the entire file as a single string (or given number of characters).
readline() Reads one line at a time
readlines() Reads all lines and returns them as a list of strings

Example:
file = open("[Link]", "r")
print([Link]()) # Reads full content
# OR
print([Link]()) # Reads first line only
# OR
print([Link]()) # Returns list of all lines
[Link]()

Fundamentals of Python Programming for Beginners 198


Python File Operations
Using read()
Reads the entire file or a specified number of characters.

SYNTAX:
[Link](size) # size is optional

Example: Partial read with read(n)


# [Link] contains: Hello Rahul
with open("[Link]", "r") as f:
print([Link](5)) # read first 5 characters
OUTPUT:
Hello

Explanation: read(5) reads only 5 characters from the current pointer.

Example: Reading File Content


f = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()
OUTPUT:
Hello Rahul
Welcome to JSS Academy of Technical Education, Noida, Uttar Pradesh.

If [Link] contains:
Hello Rahul
Welcome to JSS Academy of Technical Education, Noida, Uttar Pradesh.

Explanation:
• open() opens the file in read mode.
• read() fetches entire text from the file.
• close() frees system resources.

Using readline()
Reads one line at a time.

SYNTAX:
[Link]()

Example: Using readline()


f = open("[Link]", "r")
line = [Link]()
print(line)
[Link]()
OUTPUT:
Hello Rahul
If [Link] contains:
Hello Rahul
Welcome to JSS Academy of Technical Education, Noida, Uttar Pradesh.

Fundamentals of Python Programming for Beginners 199


Python File Operations
Explanation:
• Reads only the first line from the file.

Using readlines()
Reads all lines and returns them as a list.

SYNTAX:
[Link]()

Example: Using readlines()


f = open("[Link]", "r")
lines = [Link]()
print(lines)
[Link]()
OUTPUT:
['Hello Rahul\n', 'Welcome to JSS Academy of Technical Education, Noida, Uttar
Pradesh.\n']
If [Link] contains:
Hello Rahul
Welcome to JSS Academy of Technical Education, Noida, Uttar Pradesh.

Explanation:
• Returns each line as an element in a list, including newline characters.

Difference between read(), readline(), and readlines()


Sl.
read() readline() readlines()
No.
Reads the entire content of the Reads one line from the Reads all lines of a file and returns
1
file as a single string. file at a time. them as a list of strings.
Useful when the file size is small Useful when you want to
Useful when you need to store or
2 and you want to process process the file line by
process all lines together.
everything together. line.
Syntax:[Link](size)
Syntax:[Link](size)(If size not Syntax:[Link](hint)(Reads
3 (Reads one line; optional
given, reads entire file.) all lines; optional hint limits bytes.)
size limits characters.)
Example:python<br>f =
Example:python<br>f = open("[Link]",
Example:python<br>f =
open("[Link]", "r")<br>content "r")<br>line1 =
open("[Link]", "r")<br>lines =
4 = [Link]()<br>line2 =
[Link]()<br>print(lines)<br>f.c
[Link]()<br>print(content)<br>f. [Link]()<br>print(lin
lose()<br>
close()<br> e1,
line2)<br>[Link]()<br>
Output (for file
containing):Hello\nPython\nW Output:['Hello\n', 'Python\n',
5 Output: Hello Python
orldOutput → 'World']
'Hello\nPython\nWorld'
Reads the entire file uses more Memory efficient, reads Loads all lines into memory at
6
memory for large files. one line at a time. once, not efficient for large files.

Fundamentals of Python Programming for Beginners 200


Python File Operations
4.4 WRITING FILES IN PYTHON
Python provides two main methods for writing data to files:
• write(): Writes a single string to a file.
• writelines(): Writes multiple strings from a list/iterable.

Using write()
• write() overwrites existing content when used with 'w' mode.
• Does not add a newline (\n) automatically.
• Returns the number of characters written.

SYNTAX:
[Link](string)

Example: Using simple write()


f = open("[Link]", "w")
[Link]("Python is powerful!\n")
[Link]("File handling is easy.")
[Link]()
Output in [Link]:
Python is powerful!
File handling is easy.
Explanation:
• "w" mode creates a new file or overwrites existing content.

Example: Using write() Return value


file = open("demo_write.txt", "w")
count = [Link]("Python is fun!\n")
print("Characters written:", count)
[Link]()

# File content: Python is fun!


Output:
Characters written: 15
Note: Python is fun!

Explanation:
The returned value (15) is the number of characters written, including the newline.

Using writelines()
The writelines() method writes multiple strings from a list (or other iterable) into a file.
• It does not add newlines automatically, so you must include \n if you want line
breaks.
• Useful when writing multiple lines in one go.

SYNTAX:
[Link](list_of_strings)

Example: Writing list of lines


f = open("[Link]", "w")
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]

Fundamentals of Python Programming for Beginners 201


Python File Operations
[Link](lines)
[Link]()
Output in [Link]:
Line 1
Line 2
Line 3
Explanation:
• Writes multiple lines in one go.

Example: Mix write() and writelines()


f = open("[Link]", "w")
[Link]("Python is powerful!\n")
[Link](["Line 1\n", "Line 2\n"])
[Link]()
Output in [Link]:
Python is powerful!
Line 1
Line 2
Explanation: write() adds one string, then writelines() writes multiple lines.

Example: Using writelines() - Writing fruit names


data = ["Apple\n", "Banana\n", "Cherry\n"]
file = open("demo_writelines.txt", "w")
[Link](data)
[Link]()
Output:
Apple
Banana
Cherry
Explanation: Each list element is written exactly as it appears (with \n).

Example: Using writelines() - Writing and then reading back


# writelines() example
lines = ["First line.\n", "Second line.\n", "Third line.\n"]

file = open("writelines_example.txt", "w") # Opens file in write mode


[Link](lines) # write all lines from list
[Link]()

# read the file


file = open("writelines_example.txt", "r")
print([Link]())
[Link]()
Output:
First line.
Second line.
Third line.
Explanation:
• writelines() writes multiple strings from a list to the file.
• Each string in the list must have \n if you want it on a new line.

Fundamentals of Python Programming for Beginners 202


Python File Operations
Example: Writing multiple lines manually
# write() example
file = open("write_example.txt", "w") # open file for writing
[Link]("Hello World!\n") # write first line
[Link]("Python is fun!\n") # write second line
[Link]()

# read the file


file = open("write_example.txt", "r")
print([Link]())
[Link]()
Output:
Hello World!
Python is fun!
Explanation:
• write() writes one string at a time.
• \n is added manually to move to the next line.

Example: Writing numbers with writelines()


numbers = [str(n) + "\n" for n in range(1, 6)]
with open("[Link]", "w") as f:
[Link](numbers)
Output:
1
2
3
4
5
Explanation: Converts numbers into strings with \n and writes them all at once.

Example: Using a tuple


animals = ("Dog\n", "Cat\n", "Elephant\n")
with open("[Link]", "w") as f:
[Link](animals)
Output:
Dog
Cat
Elephant
Explanation: writelines() also works with tuples or any iterable of strings.

Example: Append mode ("a")


# If [Link] exists, this will add to the end; otherwise creates it
with open("[Link]", "a") as f:
[Link]("New entry\n")
Output:
(file keeps old content and adds New entry)
Explanation: "a" appends, it never overwrites existing content.

Example: write() + writelines() together


with open("[Link]", "w") as f:
[Link]("Header\n") # single string
Fundamentals of Python Programming for Beginners 203
Python File Operations
[Link](["Line 1\n", "Line 2\n"]) # list of strings

with open("[Link]", "r") as f:


print([Link]())
Output:
Header
Line 1
Line 2
Explanation: write() writes one string; writelines() writes many. Neither adds \n for
you.

Difference between write() and writelines()


Sl.
write() writelines()
No.
1 The write() method is used to write a The writelines() method is used to write a
single string to a file. list (or sequence) of strings to a file.
2 It writes one line or text at a time. It writes multiple lines at once (from a list
or tuple of strings).
3 Syntax: Syntax:
[Link](string) [Link](list_of_strings)
4 Example: Example:
f = open("[Link]", "w") # Example of writelines()
f = open("[Link]", "w")
[Link]("Hello Python\n")
[Link]("Welcome to File Handling") lines = ["Hello Python\n", "Welcome to File
Handling\n", "Have a nice day!"]
[Link]() [Link](lines)
print("Data written successfully using
write()") [Link]()
print("Data written successfully using
writelines()")
5 Output file ([Link]): Output file ([Link]):
Hello Python Hello Python
Welcome to File Handling Welcome to File Handling
Have a nice day!
6 Writes a single continuous string; if you Writes a list of strings; you must include
need newlines, you must add “\n” “\n” at the end of each string if you want line
manually. breaks.
7 Suitable for writing one line or small Suitable for writing multiple lines or bulk
text at a time. data efficiently.

4.5 Manipulating File Pointer Using seek()


The file pointer (or cursor) decides where the next read/write happens in a file.
By default, it starts at the beginning of the file. We can move it with seek().

seek() in Python
The seek() method is used to manipulate the file pointer (also called the file cursor),
which determines where the next read or write operation will occur. This is useful for:
• Reading or writing at specific positions
• Skipping parts of a file
• Rewinding to reread or overwrite data
• Accessing specific data without reading the entire file.

Fundamentals of Python Programming for Beginners 204


Python File Operations
SYNTAX:
file_object.seek(offset, whence=0)
Explanation:
offset: Number of bytes to move the pointer (positive or negative).
whence (optional): Reference point for offset:
0 → default: Beginning of file (default).
1 → Current pointer position (binary mode only).
2 → End of file (binary mode only).

Return Value:
• None

Note:
• File must be opened in a mode that supports seeking: 'r', 'r+', 'w+', 'a+', 'rb', etc.
• In text mode, only seek(offset, 0) with non-negative offset is reliably portable.
• In binary mode, all whence values are supported.

Related Method: tell()


file_object.tell()
Explanation:
• Returns the current position of the file pointer (in bytes from the start).

Example: Checking position after reading using tell()


with open("[Link]", "w") as f:
[Link]("Python")

with open("[Link]", "r") as f:


print([Link](3)) # Reads "Pyt"
print("Pointer:", [Link]())
Output:
Pyt
Pointer: 3
Explanation: tell() shows the file pointer is now at byte 3 (just after "Pyt").

Example: Move pointer back and check using tell()


with open("[Link]", "r") as f:
print([Link](2)) # "Py"
print("Pointer:", [Link]())
[Link](0) # reset to start
print("Pointer:", [Link]())
Output:
Py
Pointer: 2
Pointer: 0
Explanation: tell() first shows 2 (after reading "Py"), then 0 after seek(0) resets to the
beginning.

Example: Simple seek() + tell()


with open("[Link]", "w") as f:
[Link]("Python")

Fundamentals of Python Programming for Beginners 205


Python File Operations
with open("[Link]", "r") as f:
print([Link](3)) # 'Pyt'
print("Pointer:", [Link]()) # 3
[Link](0) # jump back to start
print([Link]()) # 'Python'
Output:
Pyt
Pointer: 3
Python
Explanation: tell() shows the current byte position; seek(0) resets to the start.

Example: Read with seek() and tell()


with open("[Link]", "w") as f:
[Link]("HelloWorld")

with open("[Link]", "r") as f:


print([Link](5)) # Reads "Hello"
print("Pointer:", [Link]()) # Shows position 5
[Link](5) # Move to position 5
print([Link]()) # Reads "World"
Output:
Hello
Pointer: 5
World
Explanation:
• tell() shows where the file pointer is.
• seek(5) moves it to position 5, so reading continues from "World".

Example: Read with seek() and tell() - Jump to middle


with open("[Link]", "w") as f:
[Link]("ABCDEFGH")

with open("[Link]", "r") as f:


[Link](4) # Jump to 4th position (E)
print("Pointer:", [Link]())
print([Link](2)) # Reads "EF"
Output:
Pointer: 4
EF
Explanation:
• seek(4) moves pointer to 4 (0-based).
• Reading from there gives "EF".

Example: Simple seek to beginning


with open("seek_demo.txt", "w") as f:
[Link]("Python Rocks!")

with open("seek_demo.txt", "r") as f:


print([Link](6)) # Reads "Python"
[Link](0) # Move back to start
print([Link](6)) # Reads "Python" again

Fundamentals of Python Programming for Beginners 206


Python File Operations
Output:
Python
Python
Explanation: seek(0) resets the pointer to the start.

Example: Start reading from 10th character


[Content of [Link] file here]
Python file operations are powerful.
with open('[Link]', 'r') as file:
[Link](10) # Move to the 10th character
print("Pointer position:", [Link]()) # Current position
print([Link]()) # Read from 10th character on
Output:
Pointer position: 10
le operations are powerful.
Explanation:
• The pointer skips the first 10 characters.
• tell() confirms the position.
• [Link]() reads the file starting from character 10.
Example: Seek and overwrite
with open("[Link]", "w+") as file:
[Link]("This is the original content.")

[Link](8) # Move after "This is "


[Link]("modified") # Overwrites starting at pos 8

[Link](0)
print([Link]())
Output:
This is modified content.
Explanation: Writing after seek overwrites existing text.

Example: Using whence


with open("[Link]", "w") as f:
[Link]("abcdefgh")

with open("[Link]", "r") as f:


[Link](3, 0) # From start → move to 3rd byte
print([Link](2)) # Reads "de"

[Link](-2, 2) # From end → move 2 bytes back


print([Link]()) # Reads "gh"
Output:
de
gh
Explanation:
• seek(3,0) jumps to position 3 → starts at "d".
• seek(-2,2) jumps 2 bytes before end → starts at "g".

Fundamentals of Python Programming for Beginners 207


Python File Operations
Example: Binary mode with seek
with open("[Link]", "wb") as f:
[Link](b"1234567890")

with open("[Link]", "rb") as f:


[Link](4, 0) # Move to 5th byte
print([Link](3)) # Reads b'567'

[Link](-3, 2) # 3 bytes before end


print([Link]()) # Reads b'890'
Output:
b'567'
b'890'
Explanation: In binary mode, we can also use whence=1 and negative offsets.

Example: Very Simple Demo (Beginner Friendly)


with open("[Link]", "w") as f:
[Link]("HelloWorld")

with open("[Link]", "r") as f:


print([Link](5)) # Reads Hello
[Link](5) # Jump to position 5
print([Link]()) # Reads World
Output:
Hello
World
Explanation:
• [Link](5) reads the first 5 characters → "Hello".
• [Link](5) moves the pointer to the 5th position (right after "Hello").
• [Link]() then reads from that position until the end → "World".

Example: Using seek() to Read from a Specific Position


[Content of [Link] file here]
Hello, this is a sample file.
Line 2: Python is great
# Program to demonstrate seek() for reading from a specific position
with open('[Link]', 'w') as file:
[Link]('Hello, this is a sample file.\nLine 2: Python is great!')

with open('[Link]', 'r') as file:


# Move the file pointer to the 7th byte (after "Hello, ")
[Link](7)
content = [Link]()
print("Content read after seeking to position 7:")
print(content)
Output:
Content read after seeking to position 7:
this is a sample file.
Line 2: Python is great!

Fundamentals of Python Programming for Beginners 208


Python File Operations
[Content of [Link] file here]
this is a sample file.
Line 2: Python is great!
Explanation:
• The program first creates a file [Link] and writes two lines to it.
• The file is then opened in read mode ('r').
• The seek(7) call moves the file pointer to the 7th byte (0-based index), which is
after "Hello, ".
• The read() method reads from the 7th byte to the end of the file, capturing
everything after "Hello, ".
• The with statement ensures the file is properly closed after operations.

Example: Using seek() to Read from a Specific Position


[Content of [Link] file here]
Hello, Python!
# Create a file and read from a specific position
with open('[Link]', 'w') as file:
[Link]('Hello, Python!')

with open('[Link]', 'r') as file:


[Link](7) # Move to position 7 (after "Hello, ")
content = [Link]()
print("Content from position 7:", content)
Output:
Content from position 7: Python!
[Content of [Link] file here]
Hello, Python!
Explanation:
• The file [Link] is created with the content "Hello, Python!" (13 bytes).
• The file is opened in read mode ('r').
• seek(7) moves the pointer to position 7 (after "Hello, "), where the space is.
• read() reads from position 7 to the end, outputting "Python!".

Example: Using seek() with Different whence Values


[Content of [Link] file here]
# Demonstrate seek() with whence values

with open('[Link]', 'w') as file:


[Link]('abcdefgh')

with open('[Link]', 'r') as file:


print("Initial position:", [Link]())
[Link](3, 0) # Move to 3rd byte from start
print("Position after seek(3, 0):", [Link]())
print("Content:", [Link](2)) # Read 2 bytes

[Link](-2, 2) # Move 2 bytes back from end


print("Position after seek(-2, 2):", [Link]())
print("Content:", [Link]())

Fundamentals of Python Programming for Beginners 209


Python File Operations
Output:
Initial position: 0
Position after seek(3, 0): 3
Content: de
Position after seek(-2, 2): 6
Content: gh
[Content of [Link] file here]
abcdefgh
Explanation:
• The file [Link] is created with "abcdefgh" (8 bytes).
• tell() shows the pointer starts at 0.
• seek(3, 0) moves to position 3 (character 'd').
• read(2) reads 'de'.
• seek(-2, 2) moves 2 bytes back from the end (8 - 2 = 6, character 'g').
• read() reads 'gh' to the end.

Example: Using seek() to Read from a Specific Position


[Content of [Link] file here]
abcdefghij
# Program to demonstrate seek() with different whence values

with open('[Link]', 'w') as file:


[Link]('abcdefghij')

with open('[Link]', 'r') as file:


print("Initial position:", [Link]()) # Get initial position
[Link](5, 0) # Seek to 5th byte from
beginning
print("Position after seek(5, 0):", [Link]())
print("Content from position 5:", [Link](2)) # Read 2 bytes

[Link](-3, 2) # Seek 3 bytes backward from end


print("Position after seek(-3, 2):", [Link]())
print("Content from position 7:", [Link]())

[Link](2, 1) # Seek 2 bytes forward from current


position
print("Position after seek(2, 1):", [Link]())
print("Content from position 9:", [Link]())
Output:
Initial position: 0
Position after seek(5, 0): 5
Content from position 5: fg
Position after seek(-3, 2): 7
Content from position 7: hij
Position after seek(2, 1): 9
Content from position 9: j
[Content of [Link] file here]
abcdefghij

Fundamentals of Python Programming for Beginners 210


Python File Operations
Explanation:
• The file [Link] is created with the content "abcdefghij" (10 bytes).
• The file is opened in read mode ('r').
• tell() shows the initial position as 0 (start of the file).
• seek(5, 0) moves the pointer to the 5th byte (position 5, character 'f').
• read(2) reads 2 bytes ('fg').
• seek(-3, 2) moves the pointer 3 bytes backward from the end (position 10 - 3 = 7,
character 'h').
• read() reads from position 7 to the end ('hij').
• seek(2, 1) moves the pointer 2 bytes forward from the current position (7 + 2 = 9,
character 'j').
• read() reads the remaining content ('j').

Example: Using seek() for Overwriting Specific Parts of a File


[Content of [Link] file here]
abcdefghij
# Program to demonstrate seek() for overwriting part of a file

with open('[Link]', 'w+') as file:


[Link]('This is the original content.')
print("Initial content:", [Link]()) # Won't read anything (pointer at end)

[Link](8) # Move to position 8 (after "This is ")


[Link]('modified') # Overwrite starting at position 8

[Link](0) # Move back to the beginning


content = [Link]()
print("Content after modification:")
print(content)
Output:
Initial content:
Content after modification:
This is modified content.
[Content of [Link] file here]
This is modifiedinal content.
Explanation:
• The file [Link] is opened in read-write mode ('w+'), which creates a new file or
overwrites an existing one and allows both reading and writing.
• The initial write() writes "This is the original content.".
• The first read() returns nothing because the file pointer is at the end after writing.
• seek(8) moves the pointer to position 8 (after "This is ").
• The write('modified') overwrites the next 8 bytes with "modified", resulting in
"This is modified content.".
• seek(0) moves the pointer back to the beginning, and read() reads the entire
modified content.

Fundamentals of Python Programming for Beginners 211


Python File Operations
Example: Using seek()
[Content of [Link] file here]
abcdefghij
# Writing sample data into file
file = open("seek_example.txt", "w")
[Link]("ABCDEFGH") # 8 characters
[Link]()

# Reading and moving the file pointer


file = open("seek_example.txt", "r")

print("Reading first 3 characters:")


print([Link](3)) # Reads "ABC"

# Move pointer back to the start (offset=0, from beginning)


[Link](0)
print("\nAfter seek(0):")
print([Link](4)) # Reads "ABCD"

# Move pointer to position 5 (0-based index)


[Link](5)
print("\nAfter seek(5):")
print([Link]()) # Reads from 'F' to end

[Link]()
Output:
Reading first 3 characters:
ABC

After seek(0):
ABCD

After seek(5):
FGH
Explanation:
• First, the file seek_example.txt contains:
ABCDEFGH
0 1 2 3 4 5 6 7 (positions in bytes)
• [Link](3) → Reads "ABC", pointer now at position 3.
• [Link](0) → Moves pointer to start, so reading starts again from "A".
• [Link](5) → Moves pointer to "F", reading continues from there to end.

Fundamentals of Python Programming for Beginners 212


Python File Operations
Example: Binary Mode with seek()
[Content of '[Link]' file here]
binary data: 1234567890
# Seek in binary mode
with open('[Link]', 'wb') as file:
[Link](b'1234567890')

with open('[Link]', 'rb') as file:


[Link](4, 0) # Move to 4th byte from
start
print("Content from position 4:", [Link](3).decode())
[Link](-3, 2) # Move 3 bytes back from
end
print("Content from position 7:", [Link]().decode())
Output:
Content from position 4: 567
Content from position 7: 890
Explanation:
• The file [Link] is created with 10 bytes (b'1234567890').
• In binary read mode ('rb'), seek(4, 0) moves to position 4 (byte '5').
• read(3) reads 3 bytes (b'567'), decoded to '567'.
• seek(-3, 2) moves to position 7 (10 - 3 = 7, byte '8').
• read() reads b'890', decoded to '890'.

Example: Seek Backward from end


[Content of [Link] file here]
Python file seek example demo.
with open('[Link]', 'rb') as file:
[Link](-5, 2) # Go 5 bytes before the end (binary mode)
print("Pointer position:", [Link]())
print([Link]().decode('utf-8')) # Read the last 5 bytes

Output:
Pointer position: 26
demo.
Explanation:
• File is opened in 'rb' (binary) mode for negative offset.
• seek(-5, 2) means: Move backward 5 bytes from the end.
• [Link]() gets the last 5 bytes, which is "demo.".

Note:
With the above examples, learners can:
1. Reset pointer (seek(0))
2. Jump to a character position
3. Overwrite at specific place
4. Use whence for flexible navigation
5. Handle binary files safely

Fundamentals of Python Programming for Beginners 213


Python File Operations
Parameter in Python's seek() function
The from_what parameter in Python's seek() function controls where the file pointer's
movement is calculated from. The values have these specific meanings:
Value Typical Usage
0 : The reference point is the beginning of the file.
seek(offset, 0) moves the pointer to offset bytes from the start of the file,
regardless of the current position.

1 : The reference point is the current file position. seek(offset, 1) moves the
pointer offset bytes forward (or backward, if offset is negative) from
wherever it currently is. This mode requires the file to be opened in binary
mode ('rb').

2 : The reference point is the end of the file. seek(offset, 2) moves the
pointer offset bytes from the file's end; usually, you use a negative offset to
move backward. This also requires binary mode.

Example: Demonstrating seek() with Forward and Backward Movement


[Content of [Link] file here]
abcdefghij
klmnopqrst
uvwxyz
# Create the file for demonstration (you can skip this in real usage)
with open("[Link]", "w") as f:
[Link]("abcdefghij\nklmnopqrst\nuvwxyz\n")

# Now, demonstrate seek() usage


with open("[Link]", "rb") as file:
# 1. Forward Movement: Move to the 5th byte from start
[Link](5, 0)
print("Position after forward seek:", [Link]())
print("Reading after seeking forward:", [Link](5).decode())

# 2. Backward Movement: Move 5 bytes back from the current position


[Link](-5, 1)
print("\nPosition after backward seek:", [Link]())
print("Reading after seeking backward:", [Link](5).decode())

# 3. Move backwards from the end: 7 bytes before end


[Link](-7, 2)
print("\nPosition 7 bytes before end:", [Link]())
print("Reading the last 7 bytes:", [Link]().decode())
Output:
Position after forward seek: 5
Reading after seeking forward: fghij

Position after backward seek: 5


Reading after seeking backward: fghij

Position 7 bytes before end: 26

Fundamentals of Python Programming for Beginners 214


Python File Operations
Reading the last 7 bytes: tuvwxyz
Explanation:

Forward Movement:
• [Link](5, 0): Jumps to the 5th byte from the start (0 = beginning).
• Reads 5 bytes: This prints "fghij".

Backward Movement:
• After reading, pointer moves forward; then [Link](-5, 1) moves it 5 bytes back
from the current position (1 = relative to current).
• Reads again: Prints "fghij", because the pointer was returned and the same chunk
is read again.
Backward from End:
• [Link](-7, 2): Moves pointer 7 bytes before the end of the file (2 = relative to end).
• Reads rest: Prints the last 7 bytes ("tuvwxyz").

Typical Values
Value Reference Description Mode Needed
Point
0 Beginning of file Absolute positioning from file start Text/Binary
Current file
1 pointer Relative movement to current pointer Binary only
Relative movement from end (often
2 End of file negative offset) Binary only

Example: (Error manipulating) Using seek() for Overwriting Specific Parts of a File
[Content of [Link] file here]
Hello, this is a sample file.
Line 2: Python is great!

with open('[Link]', 'r') as file:


[Link](5, 0) # Move to position 5
print("Content from position 5:", [Link]())
[Link](-10, 1) # Try to move backward (may cause error)
except IOError as e:
print(f"Error manipulating file pointer: {e}")

Output:
Content from position 5: this is a sample file.
Line 2: Python is great!
Error manipulating file pointer: [Errno 22] Invalid argument
Explanation:
• The program attempts to seek to position 5 and read the content, which succeeds.
• The seek(-10, 1) tries to move 10 bytes backward from the current position, which
may fail if the resulting position is negative, triggering the IOError.

Fundamentals of Python Programming for Beginners 215


Python File Operations
4.6 EXCEPTION HANDLING WITH FILE OPERATIONS
Using try–except–finally ensures that even if an error occurs (e.g., file not found), the
program doesn’t crash.

Example: Exception Handling with File Operations


(if file does not exist):

try:
f = open("[Link]", "r") # Trying to read a file that may not exist
content = [Link]()
print(content)
except FileNotFoundError:
print("File not found! Please check the filename.")
finally:
print("File handling process completed.")
Output: (if file does not exist):
File not found! Please check the filename.
File handling process completed.
Explanation:
• try → attempts to run risky code.
• except → handles the error gracefully.
• finally → runs no matter what (good place to close files or clean up).

4.7 Log File Analyzer


Imagine a log file with system messages. We want to count how many times "ERROR"
occurs.
Example: Count how many times "ERROR" occurs.
Sample file [Link] content:
INFO: System started
ERROR: Disk not found
INFO: User logged in
ERROR: Out of memory
error_count = 0

with open("[Link]", "r") as f:


for line in f:
if "ERROR" in line:
error_count += 1

print("Total ERROR messages:", error_count)


Output:
Total ERROR messages: 2
Explanation:
• Opens the file safely with with open(...).
• Reads line by line and checks if "ERROR" exists.
• Counts total error messages → very common in server log analysis.

Fundamentals of Python Programming for Beginners 216


Python File Operations
4.8 WORKING WITH CSV FILES
CSV stands for Comma-Separated Values. It is a simple and universal file format used
for storing tabular data (like in Excel or Google Sheets).
• Each line → represents a row
• Values inside the row → separated by commas

Note: CSV files are lightweight, easy to read, and supported by almost all programming
languages and applications.

4.8.1 Writing CSV files


Python provides the csv module, which makes creating and writing CSV files simple.

Example: Writing Student Records into CSV


import csv

# Data to write
data = [
["Name", "Age", "Branch"],
["Bharat", 37, "ECE"],
["Rahul", 35, "ECE_VLSI"],
["Vimal", 18, "CSE"],
]

with open("[Link]", "w", newline="") as f:


writer = [Link](f)
[Link](data)

print("CSV file created successfully!")

Console Output:
CSV file created successfully!
Content of [Link] (created file)
Name,Age,Branch
Bharat,37,ECE
Rahul,35,ECE_VLSI
Vimal,18,CSE
Explanation
1. data list → Each inner list is one row for the CSV file.
✓ Row 1 → Column headers.
✓ Row 2 → Bharat’s details.
✓ Row 3 → Rahul’s details.
✓ Row 4 → Vimal’s details.
2. open("[Link]", "w", newline="")
✓ "w" → Opens in write mode (overwrites existing file).
✓ newline="" → prevents extra empty lines on Windows systems.
3. [Link](data) → writes multiple rows at once.
4. Printed message confirms successful completion.

Fundamentals of Python Programming for Beginners 217


Python File Operations
4.8.2 Reading CSV files
Example: Reading the Entire CSV File
Content of [Link]:

Name,Age,Branch
Bharat,37,ECE
Rahul,35,ECE_VLSI
Vimal,18,CSE
import csv

with open("[Link]", "r") as f:


reader = [Link](f)
for row in reader:
print(row)
Output:
['Name', 'Age', 'Branch']
['Bharat', '37', 'ECE']
['Rahul', '35', 'ECE_VLSI']
['Vimal', '18', 'CSE']
Explanation:
• [Link]() reads each line as a list of strings.
• The loop prints each row one by one.

Example: Reading Only Names from CSV File


Content of [Link]:

Name,Age,Branch
Bharat,37,ECE
Rahul,35,ECE_VLSI
Vimal,18,CSE
import csv

with open("[Link]", "r") as f:


reader = [Link](f)
next(reader) # skip header
for row in reader:
print(row[0])
Output:
Bharat
Rahul
Vimal
Explanation:
• next(reader) → skips the first row (header).
• row[0] → prints the first column → Name.

Example: Using DictReader for Easy Access from CSV File (Recommended Method)
Content of [Link]:
Name,Age,Branch
Bharat,37,ECE
Rahul,35,ECE_VLSI
Fundamentals of Python Programming for Beginners 218
Python File Operations
Vimal,18,CSE
import csv
with open("[Link]", "r") as f:
reader = [Link](f)
for row in reader:
print(row["Name"], "is in branch", row["Branch"])
Output:
Bharat is in branch ECE
Rahul is in branch ECE_VLSI
Vimal is in branch CSE
Explanation:
• DictReader reads each row as a dictionary
Example: {"Name": "Bharat", "Age": "37", "Branch": "ECE"}
• Makes accessing columns easier using keys.

4.8.3 Appending CSV files


Appending means adding new data to the end without deleting existing data.

Example: Appending a New Student into CSV File


Content of [Link]:

Name,Age,Branch
Bharat,37,ECE
Rahul,35,ECE_VLSI
Vimal,18,CSE
import csv

with open("[Link]", "a", newline="") as f:


writer = [Link](f)
[Link](["Manoj", 38, "ECE"])

print("New student added!")


Console Output:
New student added!
Content of [Link] after appending:
Name,Age,Branch
Bharat,37,ECE
Rahul,35,ECE_VLSI
Vimal,18,CSE
Manoj,38,ECE
Explanation
1. open("[Link]", "a", newline="")
✓ "a" → append mode (adds data at the end, doesn’t overwrite).
✓ newline="" → prevents blank lines between rows.
2. [Link]([...])
✓ Adds one new row into the CSV file.
3. Print Statement → Confirms success.

Fundamentals of Python Programming for Beginners 219


Python File Operations
SUMMARY
Operation Python Method Explanation
Write CSV [Link], [Link]() Creates a new CSV file
Read CSV (list-based) [Link]() Reads rows as lists
Read CSV (dict-based) [Link]() Reads rows as dictionaries
[Link]() with "a"
Append CSV Adds new rows at bottom
mode

Fundamentals of Python Programming for Beginners 220


Python File Operations
Previous Year Examination Questions with Solutions

Construct a program to change the contents of the file by reversing each character
separated by comma:
Hello!!
Output
H,e,l,l,o,!,!

Solution:

Example: Reverse Each Character and Separate by Comma


If file [Link] contains: Hello!!
# Open the file in write mode and add the text
file = open("[Link]", "w")
[Link]("Hello!!")
[Link]()

# Open the file in read mode


file = open("[Link]", "r")
content = [Link]()
[Link]()

# Reverse the content and separate each character by comma


reversed_content = ",".join(content[::-1])

# Open the file again in write mode to update the content


file = open("[Link]", "w")
[Link](reversed_content)
[Link]()

print("File content has been updated successfully!")


print("Output:", reversed_content)
Output:
File content has been updated successfully!
Output: !,!,o,l,l,e,H
Explanation:
1. Write "Hello!!" into a file named [Link].
2. Read the file content using .read().
3. Reverse the string using slicing → content[::-1].
4. Insert commas between characters using ",".join(...).
5. Write the modified string back to the file.
**In this question, it is stated to reverse the file content "Hello!!", but the given output is
H,e,l,l,o,!,!. Therefore, we only need to insert commas between each character. The program
is given below.

Hello!!
Output
H,e,l,l,o,!,!

Fundamentals of Python Programming for Beginners 221


Python File Operations
Example: Separate Each Character by a Comma
If file [Link] contains: Hello!!
# Step 1: Open the file in write mode and add text
file = open("[Link]", "w")
[Link]("Hello!!")
[Link]()

# Step 2: Open the file in read mode


file = open("[Link]", "r")
content = [Link]()
[Link]()

# Step 3: Add commas between each character


new_content = ",".join(content)

# Step 4: Open the file again in write mode to update content


file = open("[Link]", "w")
[Link](new_content)
[Link]()

# Step 5: Display the updated content


print("File content has been updated successfully!")
print("Output:", new_content)
Output:
File content has been updated successfully!
Output: H,e,l,l,o,!,!
Explanation:
1. The file [Link] is created and the word Hello!! is written into it.
2. The program reads the content of the file.
3. The statement ",".join(content) inserts a comma after every character.
4. The updated string is written back into the same file.
5. The final output is displayed on the screen.

What does the readline() function return when it reaches the end of a file?

Solution:
• readline() reads one line at a time from a file.
• It includes the newline character \n if present.
• When it reaches the end of the file (EOF), it returns an empty string " ", which is
the signal to stop reading.

Example:
# Assume a file named "[Link]" with the following content:
# Hello
# World
# Python
with open("[Link]", "r") as file:
line1 = [Link]() # Reads first line
line2 = [Link]() # Reads second line
line3 = [Link]() # Reads third line

Fundamentals of Python Programming for Beginners 222


Python File Operations
line4 = [Link]() # Reaches EOF, returns empty string

print("Line 1:", [Link]()) # Output: Line 1: Hello


print("Line 2:", [Link]()) # Output: Line 2: World
print("Line 3:", [Link]()) # Output: Line 3: Python
print("Line 4:", [Link]()) # Output: Line 4: (empty, as EOF returns "")
Output:
Line 1: Hello
Line 2: World
Line 3: Python
Line 4:

Explain different file opening modes also write a Python Program to read a file and
capitalize the first letter of every word in the file.

Solution:

(Refer to the section on file opening modes.)

Python Program to read a file and capitalize the first letter of every word in the file.
Content of [Link]
rahul is faculty in ece department, jss academy of technical education, noida
uttar pradesh
india

# Program to read a file and capitalize the first letter of every word

# Open the file in read mode


file = open("[Link]", "r")

# Read the content of the file


content = [Link]()

# Capitalize the first letter of every word


capitalized_content = [Link]()

# Close the file


[Link]()

# Display the results


print("Original Content:\n", content)
print("\nCapitalized Content:\n", capitalized_content)
Output:

Original Content:
rahul is faculty in ece department, jss academy of technical education, noida
uttar pradesh
india

Fundamentals of Python Programming for Beginners 223


Python File Operations
Capitalized Content:
Rahul Is Faculty In Ece Department, Jss Academy Of Technical Education, Noida
Uttar Pradesh
India
Explanation:
• The program opens [Link] in read mode.
• It reads all text and uses the .title() function to capitalize the first letter of every
word.
• Both the original and modified contents are printed.

Write a program to reverse the contents of a file character by character, separating


each character with a comma.

Solution:
Method-1: Simple Read–Reverse–Join (same-file overwrite)
Initial content of [Link]
Hello Rahul
# Step 1: Open and read the file
file = open("[Link]", "r")
text = [Link]() # text = "Hello Rahul"
[Link]()

# Step 2: Reverse the text and add commas


reversed_text = text[::-1] # reversed_text = "luhaR olleH"
result = ",".join(reversed_text) # result = "l,u,h,a,R, ,o,l,l,e,H"

# Step 3: Overwrite the same file with the result


file = open("[Link]", "w")
[Link](result)
[Link]()
Output:
l,u,h,a,R, ,o,l,l,e,H
Explanation:
1. Open the file for reading
file = open("[Link]", "r")
✓ Opens the file named [Link] in read mode.
2. Read the content
text = [Link]()
✓ Reads all the text from the file and stores it in the variable text.
✓ Example: if file has Hello Rahul, then text = "Hello Rahul".
3. Close the file
[Link]()
✓ Always close the file after reading to free up system resources.
4. Reverse the text
reversed_text = text[::-1]
✓ [::-1] reverses the string.
✓ "Hello Rahul" becomes "luhaR olleH".
5. Add commas between characters
result = ",".join(reversed_text)
✓ join() puts a comma between each character.
✓ "luhaR olleH" becomes "l,u,h,a,R, ,o,l,l,e,H".

Fundamentals of Python Programming for Beginners 224


Python File Operations
6. Open the file again for writing
file = open("[Link]", "w")
✓ Opens the same file in write mode, which overwrites the old content.
7. Write the result into the file
[Link](result)
✓ Writes the new reversed, comma-separated text back into the file.
8. Close the file
[Link]()
✓ Saves the changes and closes the file.

Method-2: Using "utf-8" - Unicode Transformation Format (8-bit).


Initial content of [Link]
Hello Rahul
# Read -> reverse -> join -> write (same file)
with open("[Link]", "r", encoding="utf-8") as f:
s = [Link]()

with open("[Link]", "w", encoding="utf-8") as f:


[Link](",".join(s[::-1]))
Output:
l,u,h,a,R, ,o,l,l,e,H
Explanation:
1. with open("[Link]", "r") as f:
✓ Opens the file [Link] in read mode (r).
✓ The with statement automatically closes the file after reading (no need for
close()).
2. s = [Link]()
✓ Reads the entire text from the file and stores it in the variable s.
✓ Example: If the file has Hello Rahul, then s = "Hello Rahul".
3. s[::-1]
✓ Reverses the string using slicing.
✓ "Hello Rahul" becomes "luhaR olleH".
4. ",".join(s[::-1])
✓ Joins each character of the reversed string with a comma.
✓ "luhaR olleH" becomes "l,u,h,a,R, ,o,l,l,e,H".
5. Second with open("[Link]", "w") as f:
✓ Opens the same file again in write mode (w).
✓ This overwrites the old content in the file.
6. [Link](",".join(s[::-1]))
✓ Writes the reversed, comma-separated text back into the file.
Note:
What is encoding="utf-8"?
• Encoding means how characters (letters, symbols, numbers) are stored as bytes
in a computer file.
• "utf-8" stands for Unicode Transformation Format (8-bit).
• It is the most common and standard encoding used worldwide because it
supports:
✓ All English characters
✓ Special symbols
✓ Emojis
✓ Letters from all languages (Hindi, Chinese, Arabic, etc.)

Fundamentals of Python Programming for Beginners 225


Python File Operations
Example:
If your file has the text "Hello राहुल", then encoding="utf-8" ensures both English and
Hindi letters are read correctly. Without specifying it, Python might give an error.

Discuss different types of file modes in Python and explain with examples.

(Refer to the section on file modes.)

Write a program to read a CSV file and display the rows where a specific column value
exceeds a given threshold.

Solution:

Example Program:
Initial File Content [Link]
Name,Marks
Rahul,45
Bharat,78
Manoj,62
Ritesh,39
import csv

# Set threshold value


threshold = 50

# Open and read the CSV file


with open("[Link]", "r") as file:
reader = [Link](file) # Reads rows as dictionaries

print("Rows where Marks > 50:")


for row in reader:
if int(row["Marks"]) > threshold:
print(row)
Output:
Rows where Marks > 50:
{'Name': 'Bharat', 'Marks': '78'}
{'Name': 'Manoj', 'Marks': '62'}
Explanation:
1. import csv Loads the CSV module to handle file reading.
2. threshold = 50 Sets the minimum marks to filter.
3. open("[Link]", "r") Opens the file in read mode.
4. [Link](file) Reads each row as a dictionary: Example → {'Name': 'Rahul',
'Marks': '45'}
5. int(row["Marks"]) > threshold Converts the "Marks" value to integer and checks if
it's greater than 50.
6. print(row) Displays the entire row if condition is true.

Fundamentals of Python Programming for Beginners 226


Python File Operations
Write a program to read and write data from a text file. How do readline() and
readlines() work? Explain with examples.

Solution:

Method-1: Program to Read and Write Data from a Text File using with open

# ----- WRITE DATA TO FILE -----


with open("[Link]", "w") as f:
[Link]("Hello Rahul\n")
[Link]("Welcome to Python file handling.\n")
[Link]("Have a great day!")

# ----- READ DATA FROM FILE -----


with open("[Link]", "r") as f:
content = [Link]()
print("File Content:\n", content)

Output:
(File Content)
Hello Rahul
Welcome to Python file handling.
Have a great day!

Explanation
• open("[Link]", "w")
Opens the file in write mode.
✓ If [Link] does not exist → it will be created.
✓ If it already exists → its old content will be erased and replaced.
• [Link](...)
Writes lines of text into the file.
\n is used to move to the next line.
• open("[Link]", "r")
Opens the same file in read mode.
• [Link]()
Reads the entire file content as one string.
• with open(...) as f:
This is the with statement.
It automatically closes the file after the block finishes.
You do not need to call close() manually.

Method-2: Program to Write and Read from a Text File

# Step 1: Write data to a file


file = open("[Link]", "w") # open file in write mode
[Link]("Hello Rahul\n")
[Link]("Welcome to Python file handling.\n")
[Link]("Have a great day!")
[Link]() # always close the file

Fundamentals of Python Programming for Beginners 227


Python File Operations
# Step 2: Read data from the same file
file = open("[Link]", "r") # open file in read mode
content = [Link]() # read entire file content
print("File Content:\n")
print(content)
[Link]() # close after reading

Output:
(File Content)

Hello Rahul
Welcome to Python file handling.
Have a great day!

Explanation:
1. open("[Link]", "w")
✓ Opens (or creates) the file [Link] in write mode.
✓ "w" will overwrite the file if it already exists.
2. [Link](...)
✓ Writes text into the file.
✓ \n is a newline (go to next line).
3. [Link]()
✓ Saves the file and releases it. Always close after writing.
4. open("[Link]", "r")
✓ Opens the same file again, but this time in read mode.
5. [Link]()
✓ Reads the entire file as one string.
6. print(content)
✓ Displays the file content on the screen.
7. Close again after reading.

readline() and readlines() in python:


Both methods are used to read data from a text file, but they behave differently:

readline() Method
• Reads one line at a time from the file.
• Each call returns the next line as a string.
• Useful when reading large files line-by-line.

Syntax:
[Link]()

Example: Program to Read using readline()

# Create and write to file


with open("[Link]", "w") as f:
[Link]("Hello Rahul\n")
[Link]("Welcome to Python\n")
[Link]("Have a great day!\n")

Fundamentals of Python Programming for Beginners 228


Python File Operations
# Read using readline()
with open("[Link]", "r") as f:
print([Link]()) # Reads first line
print([Link]()) # Reads second line

Output:
Hello Rahul
Welcome to Python

Explanation:
• The first readline() reads "Hello Rahul".
• The second readline() reads "Welcome to Python".
• Each call reads only one line until the end of file.

readlines() Method:
• Reads all lines at once and returns them as a list of strings.
• Each line is an element in the list.
• Useful when you want to process the entire file at once.

Example: Program using readlines()


# Create and write to file
with open("[Link]", "w") as f:
[Link]("Hello Rahul\n")
[Link]("Welcome to Python\n")
[Link]("Have a great day!\n")

# Read using readlines()


with open("[Link]", "r") as f:
lines = [Link]() # Reads all lines into a list
print(lines)

Output:
['Hello Rahul\n', 'Welcome to Python\n', 'Have a great day!\n']

Explanation:
1. The file [Link] is created and three lines are written to it.
2. [Link]() reads all lines at once and stores them in a list.
3. Each element in the list is one line from the file.
4. The \n shows the newline character (end of each line).

a. What is the purpose of the seek() method in file handling? Demonstrate a program
that copies content from one file to another.

Solution:
• The purpose of the seek() method in file handling in Python is to move the file
pointer (cursor) to a specific position within a file.
• It allows the program to read or write data from any desired location instead
of only starting from the beginning of the file.

Syntax
[Link](offset, whence)

Fundamentals of Python Programming for Beginners 229


Python File Operations
• offset: Number of bytes to move the pointer.
• whence (optional): Reference point for movement.
✓ 0 → from the beginning of the file (default)
✓ 1 → from the current position
✓ 2 → from the end of the file

Example: Program demonstrating seek() operation

# Create and write to a file


with open("[Link]", "w") as f:
[Link]("Hello Rahul, Welcome to Python!")

# Read first 5 characters, then move back and read again


with open("[Link]", "r") as f:
print([Link](5)) # Reads first 5 characters
[Link](0) # Moves cursor to beginning
print([Link](10)) # Reads first 10 characters again

Output:
Hello
Hello Rahu

Explanation:
• When a file is opened, the cursor starts at position 0 (beginning).
• read(5) → reads first 5 characters and moves the cursor forward.
• seek(0) → moves the cursor back to the start.
• The next read(10) starts reading again from the beginning.

Program that copies content from one file to another.

Example 1:
# Step 1: Create [Link] and write some text into it
with open("[Link]", "w") as f1:
[Link]("Hello Students!\n")
[Link]("Welcome to ECE department JSSATE Noida\n")

# Step 2: Copy content from [Link] to [Link]


with open("[Link]", "r") as f1, open("[Link]", "w") as f2:
data = [Link]() # Read everything from [Link]
[Link](data) # Write that data into [Link]

print("Copy done!")

Output:
Copy done!

And the content of [Link] will be:


Hello Students!
Welcome to ECE department JSSATE Noida

Fundamentals of Python Programming for Beginners 230


Python File Operations
Explanation
• [Link] is created and two lines are written:
✓ "Hello Students!"
✓ "Welcome to ECE department JSSATE Noida"
• We open [Link] (read mode "r") and [Link] (write mode "w").
• We read all text from [Link] into data.
• We write data into [Link].
• Then we print Copy done! to show the task is finished.

Example 2: Program using seek() while copying file content

# Step 1: Create [Link] and write some content


with open("[Link]", "w") as f1:
[Link]("Hello Students!\n")
[Link]("Welcome to ECE department JSSATE Noida\n")

# Step 2: Open the same file for reading and another for writing
with open("[Link]", "r") as f1, open("[Link]", "w") as f2:
[Link](0) # Move the file pointer to the beginning
data = [Link]() # Read content from start
[Link](data) # Write to new file

print("File copied successfully using seek()!")

Output:
File copied successfully using seek()!

Content of [Link]
Hello Students!
Welcome to ECE department JSSATE Noida

Explanation:
• The file [Link] is created and text is written.
• seek(0) moves the file pointer back to the beginning of the file before reading.
• The entire content is then read and written into [Link].
• The message confirms that copying was successful.

Fundamentals of Python Programming for Beginners 231


Python File Operations
Example Programs
Q1. Read full file with read()
with open("[Link]", "w") as f:
[Link]("Hello\nWorld")
with open("[Link]", "r") as f:
print([Link]())
Output:
Hello
World
Explanation: read() returns the whole file content as a single string.

Q2. Read one line with readline()


with open("[Link]", "w") as f:
[Link]("First line\nSecond line")
with open("[Link]", "r") as f:
print([Link]())
Output:
First line
Explanation: readline() reads only the first line.

Q3. Read all lines with readlines()


with open("[Link]", "w") as f:
[Link]("A\nB\nC")
with open("[Link]", "r") as f:
print([Link]())
Output:
['A\n', 'B\n', 'C']
Explanation: readlines() returns list of lines.

Q4. Write single string with write()


with open("[Link]", "w") as f:
[Link]("ECE Dept")
Output:
(file contains ECE Dept)
Explanation: write() saves a string to file.

Q5. Write multiple lines with writelines()


with open("[Link]", "w") as f:
[Link](["Apple\n", "Banana\n", "Cherry\n"])
Output:
(file contains three lines)
Explanation: writelines() writes list of strings (newline must be added manually).

Q6. Append to file

Fundamentals of Python Programming for Beginners 232


Python File Operations
with open("[Link]", "w") as f:
[Link]("Line 1\n")
with open("[Link]", "a") as f:
[Link]("Line 2\n")
with open("[Link]", "r") as f:
print([Link]())
Output:
Line 1
Line 2
Explanation: mode 'a' appends without overwriting.

Q7. Seek and Tell demo


with open("[Link]", "w") as f:
[Link]("Hello Python")
with open("[Link]", "r") as f:
[Link](6)
print("Position:", [Link]())
print([Link]())
Output:
Position: 6
Python
Explanation: seek() moves pointer, tell() gives current position.

Q8. Overwrite bytes in binary file


with open("[Link]", "wb") as f:
[Link](b"ABCDEFGH")
with open("[Link]", "r+b") as f:
[Link](2)
[Link](b"zz")
[Link](0)
print([Link]())
Output:
b'ABzzEFGH'
Explanation: Binary mode allows overwriting exact bytes.

Q9. Copy file with readlines and writelines


with open("[Link]", "w") as f:
[Link]("one\ntwo\nthree\n")
with open("[Link]", "r") as src, open("[Link]", "w") as dst:
[Link]([Link]())
with open("[Link]", "r") as f:
print([Link]())
Output:
one

Fundamentals of Python Programming for Beginners 233


Python File Operations
two
three
Explanation: Copies lines from one file to another.

Q10. Handle missing file


try:
with open("[Link]", "r") as f:
print([Link]())
except FileNotFoundError:
print("File not found")
Output:
File not found
Explanation: Shows exception handling.

Q11. Count words in a file


with open("[Link]", "w") as f:
[Link]("Python is simple")
with open("[Link]", "r") as f:
print(len([Link]().split()))
Output:
3
Explanation: Splits by spaces to count words.

Q12. Read first 5 characters


with open("[Link]", "w") as f:
[Link]("ABCDEFGHIJ")
with open("[Link]", "r") as f:
print([Link](5))
Output:
ABCDE
Explanation: read(n) reads only n characters.

Q13. Iterate file line by line


with open("[Link]", "w") as f:
[Link]("Line1\nLine2\nLine3")
with open("[Link]", "r") as f:
for line in f:
print([Link]())
Output:
Line1
Line2
Line3
Explanation: File is iterable; each loop gives a line.

Fundamentals of Python Programming for Beginners 234


Python File Operations
Q14. Write numbers 1–5
with open("[Link]", "w") as f:
for i in range(1, 6):
[Link](str(i) + "\n")
Output:
(file contains numbers 1–5 each on new line)
Explanation: Loop writes numbers line by line.

Q15. Seek to middle of file


with open("[Link]", "w") as f:
[Link]("ABCDEFGHIJ")
with open("[Link]", "r") as f:
[Link](5)
print([Link]())
Output:
FGHIJ
Explanation: Pointer jumps to 5th index.

Q16. Overwrite file content


with open("[Link]", "w") as f:
[Link]("Old Content")
with open("[Link]", "w") as f:
[Link]("New Content")
Output:
(file contains New Content)
Explanation: Opening in 'w' overwrites the file.

Q17. Use with block automatically closes file


with open("[Link]", "w") as f:
[Link]("Hello")
Output:
(file contains Hello)
Explanation: with closes file automatically.

Q18. Check file pointer after read


with open("[Link]", "w") as f:
[Link]("Python")
with open("[Link]", "r") as f:
[Link]()
print([Link]())
Output:
6
Explanation: Pointer at end after reading all 6 characters.

Fundamentals of Python Programming for Beginners 235


Python File Operations
Q19. Write list with join()
fruits = ["apple", "banana", "cherry"]
with open("[Link]", "w") as f:
[Link]("\n".join(fruits))
Output:
(file contains apple, banana, cherry on separate lines)
Explanation: join() adds \n between list items.

Q20. Copy binary file


with open("[Link]", "wb") as f:
[Link](b"12345")
with open("[Link]", "rb") as src, open("img_copy.bin", "wb") as dst:
[Link]([Link]())
with open("img_copy.bin", "rb") as f:
print([Link]())
Output:
b'12345'
Explanation: Reads binary data and writes to another file.

Summary: Python File Handling Methods


Operation Method Purpose
Read file read() Reads entire file or n characters
Read line readline() Reads one line at a time
Read all lines readlines() Returns list of all lines
Write data write() Writes single string
Write multiple writelines() Writes list or tuple of strings
Move pointer seek() Moves cursor to a position
Get position tell() Returns current cursor position

Common Errors in File Handling


FileNotFoundError : When trying to open a non-existent file in read mode.
PermissionError : When you don’t have access rights to the file.
ValueError : When using seek() improperly in text mode with negative
offsets.

Fundamentals of Python Programming for Beginners 236

You might also like