50 likes | 201 Views
Files in Python. Opening and Closing. Big Picture. To use a file in a programming language You have to open the file Then you process the data in the file Then you close the file when you are done with it This is true for input files or output files. Opening a file.
E N D
Files in Python Opening and Closing
Big Picture • To use a file in a programming language • You have to open the file • Then you process the data in the file • Then you close the file when you are done with it • This is true for input files or output files
Opening a file • To use a file, you first have to open it • in Python the syntax is infile = open(“xyz.txt”, “r”) # for input (read) or outfile = open(“mydata.txt”, “w”) # for output It creates a link between that variable name in the program and the file known to the OS
Processing in general • Processing is general term • In Python there are at least 4 ways to read from an input file • And two ways to write to an output file • They all use loops in one way or another • See other talks for details
Closing a file • When you are finished with the file (usually when you are at the end of the data if it is input) • You close the file • In Python the syntax is infile.close() Works for input or output files Note: no arguments but you MUST have () !! Otherwise the function is not actually called!