This document provides an introduction to file management in Python. It discusses what files are and the two main types: text files and binary files. It explains how files are read into a file object or stream for interaction with a program. Key file operations covered include opening and closing files, reading and writing file contents line by line or all at once, and seeking to different positions within a file. The document also touches on file formats, encoding, and using the pickle module to serialize complex Python objects to files.
12. Creating a file object
myFile = open(“myFile.txt”, “r”)
• myFile is the file object.
• It contains the buffer of information.
• The open function creates the connection
between the disk file and the file object.
• The first quoted string is the file name on disk,
the second is the mode to open it (here,“r”
means to read).
Module 11 : File Management 12 of 53
14. File modes
Mode Description
‘r’ read a text file
‘w’ write a text (wipes contents)
‘a’ append to existing file
‘b’ binary file
‘+’ both read and write
Module 11 : File Management 14 of 53
• Be careful if you open a file with the ‘w’ mode. It sets an
existing file’s contents to be empty, destroying any existing
data.
• The ‘a’ mode is nicer, allowing you to write to the end of an
existing file without changing the existing contents.
17. File contents
• Once you have a file object:
• fileObject.read()
– Reads the entire contents of the file as a string
and returns it. It can take an optional argument
integer to limit the read to N bytes, that is
fileObject.read(N).
• fileObject.readline()
– Delivers the next line as a string.
Module 11 : File Management 17 of 53
25. Copy without vowels
vowels= [‘a’, ‘e’, ‘i’, ‘o’, ‘u’, ‘A’, ‘E’, ‘I’,
‘O’, ‘U’]
# File reading and writing
inFile = open("input.txt", "r")
outFile = open("output.txt", "w")
for line in inFile:
for letter in line:
if letter in vowels:
line = line.replace(letter,’’)
outFile.write(line) # written to the output file
inFile.close()
outFile.close()
Module 11 : File Management 25 of 53
35. Reading forward
• Every read/readline/readlines moves the
current pos forward.
• When you hit the end, every read will just
yield “” since you are at the end.
• You need to seek to the beginning to start
again (or close and open, seek is easier).
Module 11 : File Management 35 of 53