.. _ch05-python-IO: =============================================================== Recap & Outlook =============================================================== So far, we have learned how to use Python for programming, focused on Python's basic data types, modules, built-in functions, manipulations of them and also the mathematical programming and plotting using `numpy `_ and `matplotlib `_. 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. =============================================================== Reading Materials =============================================================== The materials of this chapter in part have been adopted and modified from: * `Scipy Lecture Note `_, * `Think Python by Allen B. Downey `_, * `Prof. LeVeque's (Univ. of Washington) online note on Python `_. =============================================================== 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 .. code-block:: python >>> f=open('output','w') >>> type(f) >>> f.write('Welcome to AMS 129 \nwe love scientific computing!') 49 >>> f.close() To read from a file .. code-block:: python >>> f=open('output','r') >>> fread=f.read() >>> print(fread) Welcome to AMS 129 we love scientific computing! >>> f.close() To add more lines, open the file with mode ``a`` as a second parameter for append .. code-block:: python >>> f=open('output','w') >>> f.write('Welcome to AMS 129 \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 .. code-block:: python >>> f=open('output','r') >>> s=f.read() >>> print(s) Welcome to AMS 129 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 .. code-block:: python >>> f=open('output','r') >>> for line in f: ... print(line) ... Welcome to AMS 129 we love scientific computing! Python is fun to learn >>> f.close() You may notice that a blank line has been inserted in every ``line`` variable. This is because the escape character, ``\n``, is recognized as a blank line. If you want to delete the escape character, you may use the ``strip`` method. .. code-block:: python >>> f = open('output', 'r') >>> for line in f: ... print(line.strip()) ... Welcome to AMS 129 we love scientific computing! Python is fun to learn >>> f.close() If we do the same file iteration after ``f.close()`` *without* ``f=open('output','r')``, we will get an error message .. code-block:: python >>> for line in f: ... print(line) ... Traceback (most recent call last): File "", line 1, in 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) ------------------------------------------------------------------------------- ``with`` statement ------------------------------------------------------------------------------- In the previous examples, you may noticed that the general code structure of the input/output of the Python. For example, .. code-block:: python f=open(file_name, file_mode) # Do something with file as f f.close() Actually, you don't need to close the file. When your python script is over, the Python interpreter will close the file automatically, even though there is no ``close`` method given. However, by writing the ``close`` statement, your code is more easy to follow, (to human) and also it prevents the further error(s). Practically, a lot of Python programmer loves to handle the file with ``with`` statement. .. code-block:: python with open(file_name, file_mode) as f: # Do something with file as f # If exit this block, the file will be closed automatically. In this manner, all you file handling code will be presented inside of this block, and you can assume ``f.close()`` statement by exiting the block. ------------------------------------------------------------------------------- Command line input arguments ------------------------------------------------------------------------------- If you want to give input argument(s) to your program with command line, say, for instance, .. code-block:: console $ ./your_python_program.py YourArgument1 YourArgument2 In this case, you can use the ``sys`` module. .. code-block:: python import sys arg1 = sys.argv[1] arg2 = sys.argv[2] ... As you can see in the above example, your first command line input argument is taken as ``sys.argv[1]``. But wait, the index for Python start from 0. Then, what is the ``sys.argv[0]``? The answer is simple; the file name of your program itself. See the following example. .. literalinclude:: ./codes/sys_arg.py :language: python :linenos: If you execute this file as, .. code-block:: console $ python3 sys_arg.py aa bb cc sys_arg.py aa bb cc ------------------------------------------------------------------------------- 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.