[go: up one dir, main page]

0% found this document useful (0 votes)
8 views5 pages

Unit - 4 File Handeling

The document provides an overview of file operations in Python, including opening, reading, writing, and manipulating file pointers. It details various file modes, reading methods (read, readline, readlines), and writing methods (write, writelines), along with examples. Additionally, it covers binary file operations and the use of seek() and tell() functions for precise file pointer management.

Uploaded by

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

Unit - 4 File Handeling

The document provides an overview of file operations in Python, including opening, reading, writing, and manipulating file pointers. It details various file modes, reading methods (read, readline, readlines), and writing methods (write, writelines), along with examples. Additionally, it covers binary file operations and the use of seek() and tell() functions for precise file pointer management.

Uploaded by

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

Python File Operations

Python provides various built-in functions for handling files. Working with files allows you to
read from and write to external data sources, making your programs more flexible and capable of
handling data from various inputs.

1. Opening and Closing Files

In Python, you use the open() function to open a file. After performing file operations, it’s
essential to close the file using the close() method to free up system resources.

file = open("example.txt", "r") # Open in read mode


# Perform file operations here
file.close() # Close the file after operations

The open() function takes two main arguments:

 File name: The name of the file to open.


 Mode: The mode in which to open the file (default is "r" for read).

Common File Modes:

 "r" - Read mode (default). Opens the file for reading. Throws an error if the file does not
exist.
 "w" - Write mode. Opens the file for writing and overwrites existing content.
 "a" - Append mode. Opens the file for writing but appends to the end if content already
exists.
 "r+" - Read and write mode. Opens the file for both reading and writing.

2. Reading Files

Python offers several methods to read from a file:

a) read()

The read() function reads the entire content of the file as a single string.

with open("example.txt", "r") as file:


content = file.read()
print(content)

You can also specify the number of bytes to read. For example, file.read(5) reads the first 5
characters.
b) readline()

The readline() function reads a single line from the file. Each call to readline() moves the
pointer to the next line.

with open("example.txt", "r") as file:


line = file.readline()
print(line) # Prints the first line

Using readline() in a loop allows you to read all lines one by one.

with open("example.txt", "r") as file:


line = file.readline()
while line:
print(line.strip()) # Strip to remove newline characters
line = file.readline()

c) readlines()

The readlines() function reads all lines in the file and returns them as a list of strings, with
each line as a separate element.

with open("example.txt", "r") as file:


lines = file.readlines()
print(lines) # Output: List of lines in the file

3. Writing to Files

Python provides two main methods for writing to files: write() and writelines().

a) write()

The write() function writes a string to the file.

with open("output.txt", "w") as file:


file.write("Hello, World!\n",)
file.write("This is a new line.")

If the file does not exist, Python will create it. Be cautious when using "w" mode, as it will
overwrite the file if it already exists.

b) writelines()

The writelines() function writes a list of strings to the file.

lines = ["First line\n", "Second line\n", "Third line\n"]


with open("output.txt", "w") as file:
file.writelines(lines)
Note: writelines() does not automatically add newlines, so you need to include "\n" at the
end of each line.

4. Manipulating the File Pointer with seek()

The seek() function allows you to move the file pointer to a specific position within the file.
This is useful when you want to read or write from a specific location.

 seek(offset, whence):
o offset: The position to move to.
o whence: The reference position:
 0 - Beginning of the file (default).
 1 - Current position.
 2 - End of the file.

Example:

with open("example.txt", "r") as file:


file.seek(10) # Move pointer to the 10th byte
content = file.read()
print(content)

This will start reading the file from the 10th byte.

5. Examples of File Operations

Example 1: Reading and Printing File Content Line by Line

with open("example.txt", "r") as file:


for line in file:
print(line.strip())

Example 2: Writing and Appending Content to a File

# Writing new content


with open("output.txt", "w") as file:
file.write("This is the first line.\n")

# Appending more content


with open("output.txt", "a") as file:
file.write("This is an appended line.\n")

Example 3: Using seek() and tell()


The tell() function returns the current position of the file pointer.

with open("example.txt", "r") as file:


print(file.tell()) # Output: 0 (start of the file)
file.read(5)
print(file.tell()) # Output: 5 (pointer moved 5 bytes)
file.seek(0) # Move back to the start
print(file.read(5)) # Reads the first 5 characters again

6. Putting It All Together: File Copy Program

This example reads from one file and writes its content to another file.

with open("source.txt", "r") as source_file:


with open("destination.txt", "w") as dest_file:
for line in source_file:
dest_file.write(line)

1. Open in Binary Mode: ("rb", "wb", etc.)


o Use "rb" (read binary) to work with byte-level data, allowing nonzero end-
relative seeks.
2. Seek with file.seek(-10, 2):
o Moves the file cursor 10 bytes before the end of the file.
3. file.read():
o Reads the remaining bytes starting from the current cursor position.
4. decode():
o Converts binary data back to a string for display.
5. Binary mode allows precise byte-level manipulation.

# Open a file in read mode

with open("example.txt", "rb") as file:

# Move to the 5th byte from the beginning of the file

file.seek(5, 0)

file.tell()

print(file.read(10).decode()) # Read the next 10 bytes

print(file.tell())

# Move 3 bytes forward from the current position

file.seek(3, 1)
print(file.tell())

print(file.read(5).decode()) # Read the next 5 bytes

# Move 10 bytes backward from the end of the file

file.tell()

file.seek(-10, 2)

print(file.read(10).decode()) # Read the last 10 bytes

Summary

 Reading Functions:
o read(): Reads entire content or a specified number of bytes.
o readline(): Reads one line at a time.
o readlines(): Reads all lines and returns a list.
 Writing Functions:
o write(): Writes a single string.
o writelines(): Writes a list of strings.
 File Pointer Manipulation:
o seek(): Moves the file pointer to a specified location.
o tell(): Returns the current position of the file pointer.

Understanding and using these file operations allow you to manage file data effectively in
Python programs.

You might also like