Accessing Files
open
This function returns a file
object. The usage is open(file_name, mode)
, where
file_name
is the name of a file, and mode
is the mode
in which you are opening the file.
Mode | What it means |
---|---|
"r" | This opens a file for reading |
"b" | This opens a file in binary mode. It can be combined with any of the other modes. |
"w" | This opens a file for writing; if the file exists, it is clobbered, if not, it is automatically created. |
"a" | This opens a file for appending. Things get written at the end of an existing file. |
Get the file sampler.txt
on the left and we will play
with it.
Get with
it!
The Libraries os
and os.path
These let you interact with your file system in a more or less platform-independent way.
chdir(path) getcwd() os.listdir(,[dirname]) os.remove(file_name) os.is_dir(file_name) os.is_file(file_name) os.path.abspath(path) os.path.exists(file_name) os.getsize(file_name)
import sys
donor_file = sys.argv[1]
recipient_file = sys.argv[2]
fp_in = open(donor_file, "r")
fp_out = open(recipient_file, "w")
for line in fp_in:
fp_out.write(line)
fp_in.close()
fp_out.close()