File Function in Python
R lallawmawmi
Msc II
semester
007
File Handling in Python
Explore essential file handling functions in Python:
write(), writelines(), tell(), and seek(). This presentation provides a
brief introduction to these functions.
write()
Writes a string to a file.
writelines()
Writes multiple lines from a list.
tell()
Returns the current file position.
seek()
Moves the file pointer to a specific position, offering
control over where to read and write.
Introduction to File Handling
handling in Python refers to the process of reading from and writing to files using Python. It allows you to interact with files
stored on your computer, like text files, CSV files, or even images. You can open, read, write, and close files in Python using
built-in functions.
File Operations Key Functions
• Reading (r): Extract data from a file. Python provides built-in functions to manipulate files.
• Writing (w): Overwrite data in a file. Key functions include write(), writelines(), tell(), and
seek().
• Appending (a): Add data to an existing file.
• Reading & Writing (r+, w+, a+): Combine operations.
The write() Function
1 Definition
Writes a string to a file.
Overwriting if opened in “w“ mode
If "a" mode is used, it append data.
Requires string input[use (\n) for new
lines]
2 Example
With open("example.txt", "w") as f:
f.write("Hello, Python!")
Output: Hello Python
The writelines() Function
Definition Example
Output
Writes multiple lines example.txt:
from a list to a file. lines = ["Python Python is fun!
Does not add is fun!\n", "File File handling is
newlines (\n) handling is useful.
automatically useful.\n"]
with
open("example.txt"
, "w") as f:
f.writelines(lines
)
tell() Function
Definition
Returns the current position
of the file pointer in bytes.
Useful for tracking where
reading and writing occurs.
Beginning
With open("example.txt", "r") as
f:
print(f.tell()) # Output: 0
f.read(5)
print(f.tell()) # Output: 5
seek() Function Offset
Position to move to (in bytes).
Definition 2
Moves the file pointer to a specific position.
1
Whence: 0
3 Beginning of file (default).
Whence: 2 5
End of file.
4
Whence: 1
Example: Current position.
with open("example.txt", "r") as f:
f.seek(10) # Moves to 10th byte
print(f.read())
Function Comparison
Function Purpose Key Feature
write() Writes a single string Overwrites if not in append
mode
writelines() Writes multiple lines Requires a list of strings
tell() Gets current file position Useful for tracking read/write
seek() Moves file pointer Navigates within a file
THANK YOU