Important Python File Management Functions
|
Method |
Use |
Simple Example |
|
open() |
Opens a file for
reading, writing, or other operations. |
file =
open("data.txt", "r") |
|
read() |
Reads the complete
content of a file. |
data =
file.read() |
|
readline() |
Reads one line from a
file at a time. |
line =
file.readline() |
|
readlines() |
Reads all lines as a
list |
lines =
file.readlines() |
|
write() |
Writes a string or text
to a file. |
file.write("Hello") |
|
writelines() |
Writes multiple lines |
file.writelines(["A\n",
"B\n"]) |
|
close() |
Closes a file |
file.close() |
|
seek() |
Moves the file pointer
to a specified position. |
file.seek(0) |
|
tell() |
Returns the current
position of the file pointer. |
pos =
file.tell() |
|
readable() |
Checks whether the file
is open for reading. |
file.readable() |
|
writable() |
Checks whether the file
can be written |
file.writable() |
|
truncate() |
Removes part of the
file content after a specified position. |
file.truncate(10) |
Important for beginners:
For basic file
management, students should focus mainly on:
open() → read() / write()
→ close()
and preferably use:
with
open("data.txt", "r") as file:
data = file.read()
print(data)
The methods seek(), tell(),
readable(), writable(), and seekable() are useful when you start working with file
pointers and more advanced file operations for your project work.
No comments:
Post a Comment