Unit - 4 File Handeling
Unit - 4 File Handeling
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.
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.
"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
a) read()
The read() function reads the entire content of the file as a single string.
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.
Using readline() in a loop allows you to read all lines one by one.
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.
3. Writing to Files
Python provides two main methods for writing to files: write() and writelines().
a) write()
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 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:
This will start reading the file from the 10th byte.
This example reads from one file and writes its content to another file.
file.seek(5, 0)
file.tell()
print(file.tell())
file.seek(3, 1)
print(file.tell())
file.tell()
file.seek(-10, 2)
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.