Python Files
Python Files
• 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.
• 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
• File.write(‘Some Text’)
• File.writelines(lines)