Presentation - Files in Python

Download Report

Transcript Presentation - Files in Python

Python focus – files
Opening a file
The open keyword returns a file object
Optional
argument
myFile = open('C:\file.txt', arg)
The second argument controls whether we:
•
•
•
•
'r' : read from the file
'w' : write to the file
'r+': read and write to the file
'a' : append to the file
The default mode is 'r'.
•
Also, add a 'b' (eg, 'rb' ) if you intend to write to a binary file
Python focus – files
Working with file objects
File objects have many useful methods
myFile.read(size) : read size characters into string
myFile.readline() : read one line into string
myFile.list() : read all lines into a list of strings
We can iterate over lines in a file object!
for line in myFile:
print line
The above will read in each line in turn until EOF
Python focus – files
Writing to file objects
File objects specifically write strings
myFile.write('Wombats are best\n')
myVar = 100
myFile.write(str(myVar))
Use the str function to convert other types to strings
a = str(['A','C','G','T'], 99)
Advanced: structured data can be saved with json
Python focus – files
Miscellaneous file methods
tell and seek relate to positions in a file
myPosition = myFile.tell()
print myPosition # integer w/ current place
myFile.seek(100) # go to the 100th character
myFile.seek(offset, from)
from can take the values:
• 0 : beginning of file
• 1 : current file position
• 2 : end of file
Python focus – files
Tidying up
close will release memory
myFile.close()
print myFile.closed() # should print True