files in python output techniques. outputting to a file there are two ways to do this in python –...

4
Files in Python Output techniques

Upload: jason-shields

Post on 29-Jan-2016

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Files in Python Output techniques. Outputting to a file There are two ways to do this in Python – print (more familiar, more flexible) – write (more restrictive)

Files in Python

Output techniques

Page 2: Files in Python Output techniques. Outputting to a file There are two ways to do this in Python – print (more familiar, more flexible) – write (more restrictive)

Outputting to a file

• There are two ways to do this in Python– print (more familiar, more flexible)– write (more restrictive)

Page 3: Files in Python Output techniques. Outputting to a file There are two ways to do this in Python – print (more familiar, more flexible) – write (more restrictive)

Using print to output to a file

• You add one argument to the print function call. At the end of the argument list, put “file=“ followed by the name of the file object you have opened for output

• Example print(“hi”, a, c*23, end=“”, file= outfile)• You can use anything in this print that you would in

printing to the screen, end=, sep=, escaped characters, etc.

• Default end= and sep=, so gives a newline at the end of every print unless you give different value

• Note it says file=outfile, NOT file = “abc.txt”

Page 4: Files in Python Output techniques. Outputting to a file There are two ways to do this in Python – print (more familiar, more flexible) – write (more restrictive)

Using write to output to a file

• write is a method, similar to the Text object in the graphics package

• it is called by the output file object (dot notation)• It is allowed ONE and only one STRING argument, so

you have to convert numbers to strings and concatenate strings together to make one argument

• Example outfile.write(“hi”+str(ct)+”\n”)• Does NOT output a newline automatically, if you

want one, you have to put one in the string