CHAPTER 14: FILE PROCESSING
14.1 FILE OPERATIONS IN PYTHON
14.1.1 Opening Files
<PYTHON>
# Read mode
file
=
open
(
"data.txt"
,
"r"
)
# Write mode (overwrites)
file
=
open
(
"data.txt"
,
"w"
)
# Append mode
file
=
open
(
"data.txt"
,
"a"
)
14.1.2 Reading Files
<PYTHON>
# Read entire file
content =
file
.read()
# Read line by line
line =
file
.readline()
# Read all lines into list
lines =
file
.readlines()
14.1.3 Writing Files
<PYTHON>
# Write string
file
.write(
"Hello
\n
"
)
# Write list of strings
file
.writelines([
"Line 1
\n
"
,
"Line 2
\n
"
])
14.1.4 Closing Files
<PYTHON>
file
.close()
# Or use context manager (auto-close)
with
open
(
"data.txt"
,
"r"
)
as
file
:
content =
file
.read()
14.2 RANDOM FILE ACCESS
14.2.1 Direct Access
<PYTHON>
import
struct
# Write record at specific position
def
write_record
(
file
,
position
,
record
):
file
.seek(position * record_size)
file
.write(struct.pack(
'i10s'
, record[
'id'
], record[
'name'
].encode()))
# Read record at specific position
def
read_record
(
file
,
position
):
file
.seek(position * record_size)
data =
file
.read(record_size)
return
struct.unpack(
'i10s'
, data)
Revision #1
Created 2026-03-16 12:19:37 UTC by Samuel Lee
Updated 2026-03-16 12:19:45 UTC by Samuel Lee