5
Files in Python Opening and Closing

Files in Python

Embed Size (px)

DESCRIPTION

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. - PowerPoint PPT Presentation

Citation preview

Page 1: Files in Python

Files in Python

Opening and Closing

Page 2: Files in Python

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

Page 3: Files in Python

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)oroutfile = open(“mydata.txt”, “w”) # for output It creates a link between that variable name in the program and the file known to the OS

Page 4: Files in Python

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

Page 5: Files in Python

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 filesNote: no arguments but you MUST have () !!Otherwise the function is not actually called!