Download presentation
Presentation is loading. Please wait.
Published byFrancis Charles Modified over 8 years ago
1
Python focus – files The open keyword returns a file object Opening a file myFile = open('C:\file.txt', arg) Optional argument 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
2
Python focus – files File objects have many useful methods Working with file objects 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! The above will read in each line in turn until EOF for line in myFile: print line
3
Python focus – files File objects specifically write strings Writing to file objects 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
4
Python focus – files tell and seek relate to positions in a file Miscellaneous file methods myPosition = myFile.tell() print myPosition # integer w/ current place myFile.seek(100) # go to the 100 th character myFile.seek(offset, from) from can take the values: 0 : beginning of file 1 : current file position 2 : end of file
5
Python focus – files close will release memory Tidying up myFile.close() print myFile.closed() # should print True
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.