actions are automatically run to close the filesregardless of exception outcomeswith open('data'as finopen('results'' 'as foutfor line in finfout write(transform(line)context manager-dependent code like this seems to have become more common in recent yearsbut this is likely at least in part because newcomers are accustomed to languages that require manual close calls in all cases in most contexts there is no need to wrap all your python file-processing code in with statements--the files object' autoclose-on-collection behavior often sufficesand manual close calls are enough for many other scripts you should use the with or try options outlined here only if you must closeand only in the presence of potential exceptions since standard python automatically closes files on collectionthoughneither option is required in many (and perhaps mostscripts input files reading data from external files is just as easy as writingbut there are more methods that let us load data in variety of modes input text files are opened with either mode flag of (for "read"or no mode flag at all--it defaults to if omittedand it commonly is once openedwe can read the lines of text file with the readlines methodc:\temppython file open('data txt'lines file readlines(for line in linesprint(lineend=''hello file worldbye file world open input file object'rdefault read into line string list but use file line iterator(aheadlines have '\nat end the readlines method loads the entire contents of the file into memory and gives it to our scripts as list of line strings that we can step through in loop in factthere are many ways to read an input filefile read(returns string containing all the characters (or bytesstored in the file file read(nreturns string containing the next characters (or bytesfrom the file file readline(reads through the next \ and returns line string file readlines(reads the entire file and returns list of line strings file tools