Save
Computing (Intermediate Python)
Files
Save
Share
Learn
Content
Leaderboard
Learn
Created by
Darsh Pimpalgaonkar
Visit profile
Cards (7)
Opening a file
1. Use the built-in
open
() command
2. Specify the file name
3. Optionally specify the
mode
(read, write, append, etc.)
Reading file contents
1. Use
file.read()
to read the
entire
file
2. Use file.readlines() to read the file
line-by-line
into a
list
3. Use a
for loop
to iterate over the
lines
in the file
file.read(size)
Reads a specified number of
characters
from the file
If we try to write from within a file that we have opened in
read mode
we get an error that says that this is not
writable
If the file doesn't exist already then
opening
it in
write mode
will
create it
If the file does exist then opening it in write mode will
overwrite
it
To avoid what? a file we can use a
lowercase
a for appending to the file
To avoid
overwriting
a file we can use a lowercase a for appending to the file