80 likes | 205 Views
File Input Output. Alexandra Stefan CSE 1310 University of Texas at Arlington. File Input Output. In order to work with a file on disk, you need to open a connection (pipe) between the file and your program. In Python, it is easy to create this connection: file_obj = open( filename, mode )
E N D
File Input Output Alexandra Stefan CSE 1310 University of Texas at Arlington
File Input Output • In order to work with a file on disk, you need to open a connection (pipe) between the file and your program. In Python, it is easy to create this connection: file_obj = open(filename, mode) • mode can be: • r (read), w (write), a (append at the end of the file) • rU(read and have Python worry about the newline character) • r+, w+, a+ (read and write) • Important! After finishing working with a file, close it! file_obj.close()
Read data from a file • Read one line at a time using a for loop: for line infile_object: # use the line string here • Read one line: file_obj.readline() • Read all the file at once: file_obj.readlines() • Returns a list that has an element for each line of the file file_obj.read() • Returns a string that has all the contents of the file. Use it together with the str method splitlines() to get access to individual lines. • When given an argument n, reads n bytes (if possible).
The current position in a file • file_objkeeps track of the current location in the file. It always operates at that location (e.g. when you read or write to the file). • The current position in the file (as number of bytes from the beginning of the file): file_obj.tell() • Change the current position (move at different locations in the file) using the seek(position) method: file_obj.seek(offset, from_what) – offset: in bytes – possible values for from_what: 0 (begin of file), 1(current position), 2 (end of file), default value: 0 • Example (go back to the beginning of the file): file_obj.seek(0)
Write to a file • Writes the string my_str to the file file_obj: print(my_str, file = file_obj)
Error Handling • Construct: try : # code that can raise (generate) an error exceptErrorName: # action to take when error ErrorName happened • Example: filenm= input("file name:") try: file_obj = open(filenm, 'r') for ln in file_obj: print(ln) except IOError: print("File not found:", filenm)
Summary • file_obj = open(filename, "r") • Read data: for line infile_object: file_obj.readlines() file_obj.read()- use with str method splitlines(). file_obj.readline() • file_obj.seek(offset, from_what) • print(my_str, file = file_obj • file_obj.close() • Error handling: try…except
Processing lines from files • Remove the end of line character • For those used with C/C++: • no EOF function in Python • Use an iterator (for) to read over the lines of the file • When reaches the end of the file, the reading of data from file returns the empty string (different from an empty line string which has the newline character in it)