Recap & Outlook

So far, we have learned how to use Python for programming, focused on Python’s basic data types, modules, built-in functions, and manipulations of them.

In this short chapter we extend our knoweldge little bit further so that we can use Python to

  1. produce data inputs and outputs,
  2. run Python commands to interact with operating systems,
  3. learn how to debug efficiently,
  4. briefly look at a quick example of object-orient programming.

In the following chapter, we are going to learn mathematical programming and plotting using numpy and matplotlib in depth.

Reading Materials

The materials of this chapter in part have been adopted and modified from:

Python inputs and outputs

Read and write files

To be exhaustive, here are some information about input and output in Python. We write or read strings to/from files (other types must be converted to strings). To write onto a file

>>> f=open('output','w')
>>> type(f)
<type 'file'>
>>> f.write('Welcome to AMS 209 \nwe love scientific computing!')
>>> f.close()

To read from a file

>>> f=open('output','r')
>>> fread=f.read()
>>> print fread
Welcome to AMS 209
we love scientific computing!
>>> f.close()

To add more lines, open the file with mode a as a second parameter for append:

>>> f.write('Welcome to AMS 209 \nwe love scientific computing!')
>>> f.close()
>>> f=open('output','a')
>>> f.write('\nPython is fun to learn')
>>> f.close()

To see how it is changed now:

>> f=open('output','r')
>>> s=f.read()
>>> print s
Welcome to AMS 209
we love scientific computing!
Python is fun to learn
>>> f.close()

See also For more details: https://docs.python.org/tutorial/inputoutput.html

Iterating over a file

A file can be used as an iterable in Python:

>>> for line in f:
...     print line
...
Welcome to AMS 209

we love scientific computing!

>>> f.close()

If we do the same file iteration after f.close() without f=open('output','r'), we will get an error message:

>>> for line in f:
...     print line
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file

File modes

  • Read-only: r
  • Write-only: w
  • Append a file: a
  • Read and Write: r+
  • Binary mode: b (use for binary files, especially on Windows)

Exercise

  1. Write a simple routine that creates n many files with names junk_1.txt, ..., junk_n.txt, each of which contains its file name, e.g., This is junk_5.txt.
  2. Write a simple routine that reads the contents of the files you just created.