Files and file objects (in Python)

15
Files Python SIG – PYA Class 5 – 7/11/15

Transcript of Files and file objects (in Python)

Page 1: Files and file objects (in Python)

Files

Python SIG – PYA Class 5 – 7/11/15

Page 2: Files and file objects (in Python)

(Revision of) Tuples

• Tuples are “immutable lists”• A tuple is not ‘()’ it is ‘,’• ‘count’ and ‘index’ methods• You can slice, and (negative) index tuples, like lists• You can use ‘in’ to see if a tuple contains a

particular element• You can convert a list to a tuple and vice versa

with tuple() and list()

Page 3: Files and file objects (in Python)

(Revision of) Dictionaries

• key – value pairs• keys have to be immutable• values don’t• dict methods – mainly .keys(), .values()

and .items()• They return a list, list and list of tuples

repectively

Page 4: Files and file objects (in Python)

(Revision of) Dictionaries

• dict[valid_key] = corresponding_value• dict[invalid_key] gives a KeyError• .get(key, default_value) when we don’t want

the program crashing because of KeyErrors• .keys() won’t return alphabetically sorted list• Can use sorted() or .sort()• sorted() preferred (other won’t work in Py3)

Page 5: Files and file objects (in Python)

(Revision of) try except else finally

try:#potentially dangerous code

except TypeError, err_info:print 'type’, err_info

except ImportError, err_info:print ‘import’, err_info

else:print ‘no errors’

finally: # cleanup code (like closing a file)

Page 6: Files and file objects (in Python)

(Revision of) assert

• assert condition, ‘Error info’• If condition evaluates to False, an

AssertionError occurs• To make program “fail fast”• You’ll know where it happened

Page 7: Files and file objects (in Python)

(Revision of) raise

• raise Exception(“Error!”)• Again, “fail fast”• Can replace error description with our own• A list of exceptions can be found on the online

documentation – https://docs.python.org/2/library/exceptions.html

Page 8: Files and file objects (in Python)

(Revision of) with

• Mainly used for file r/w operations• Alternative to try except in these cases• with open(‘filename.txt’) as f1:

f1.close()

Page 9: Files and file objects (in Python)

FileIO

• File objects are used for rw operations• f1 = open(‘filename.txt’, ‘r’)• (no, not that f1)• ‘r’ is by default• ‘w’ creates file if it doesn’t exist, erases if it

does• ‘a’ is used to preserve data

Page 10: Files and file objects (in Python)

Assignment

• Write a program in the Python interpreter to print the name and information in help() of all file methods that do not start with ‘__’ (two underscores).

• To those who have finished, read them!

Page 11: Files and file objects (in Python)

Files and File objects

• .read() is useful if the file is small. (basically, can fit in RAM) It reads the entire file as a string.

• .readline() reads a single line. (defined by line endings \n \r \r\n depending on OS)

• .readlines() returns a list of all lines• .seek(0) goes to the beginning of the file• Think of the file object as a DVD player

Page 12: Files and file objects (in Python)

Files and File objects

• .write() and .writelines() are used to write to a file. The first one takes a string argument and second one a sequence of strings.

• Don’t forget to add newlines.• Don’t forget to close files.• Most of these methods have optional size

arguments.

Page 13: Files and file objects (in Python)

with

• Files can be opened multiple times• with open(‘filename.txt’) as f1:

# do something# no need to end with f1.close()

• Always closes the file; no matter what.

Page 14: Files and file objects (in Python)

Assignment

• Using a single file object, first read a .txt file and print its contents. Then ask the user whether to erase the contents or add something and extend the file.. Write the data entered by the user to the file if the user chooses the second option.

Page 15: Files and file objects (in Python)

Thanks!

Pranav S Bijapur, ECE, BMSCE, Bangalore

[email protected] Telegram - @pranavsb