Python Files
• You cant always rely on using information entirely within your
application
• Sometimes you need to read information from a file or write the
information to a file.
• In other situations you need to be able to open and update an existing
file in place
File Processing
• You open a file using the built in open() function.
• The basic format of the open() function is
• File = open(filename [,mode [,bufsize]])
Reading from a file
• Reading information from a file is handled in two basic ways: byte by
byte or line by line
• Byte by byte format is most useful when you are reading binary data
or when you are not going to be processing the information on a line
by line basis
• The line by line mode is best used when you expect to process the
information on a line by line basis – say when processing a log file
• The line by line mode has two separate modes : either you read a single
line from the file or you read all the lines in the file at one time
• Line by line
• Line = file.readline()
• The line returned by the readline method includes the trailing line-
termination characters, so you will need to use the string.rstrip() method
to take the new line off in many situations
• Different platforms use different line-termination characters, and
python recognizes the appropriate line-termination character for your
platform when reading a file.
• However python does not recognize the line termination characters
for platforms other than the current platform
• For example you can read a unix file line by line on a unix system , but
on a mac , the same unix file would appear as one big line to the MAC
version of python
Getting all the lines
• You can read all of the lines from a single file using the readlines()
method on an active file object
• For example you can read the entire file into a list using
• Lines = myfile.lines()
Byte by Byte
• You can also use the read() method to read a specific number of bytes
from a file
• Record = file.read(512)
Writing to a file
• Writing information to a file is usually just a case of calling the write()
or writelines() methods
• The write() method writes a single string
• The writelines() method actually only writes a list of strings to the file
• File.write(‘Some Text’)
• File.writelines(lines)