Introduction to Python


Contents

How to install Python on Linux
How to run a Python program
The basic of Python codes
Data expressions
Built-in functions in Python
Interactive input/output
Conditional statement for Python
Loop structure for Python
Creating your own functions
Python modules
Reading/writing files for Python
Error handling code
Object Oriented Programming (OOP)
Tkinter package for GNU programming


Reading/writing files for Python

The open() command can read or write out an external file. The second argument of open() specifies read (r) or write (w) a file. The following example is reading a file:
file0 = open("python.txt","r")
for line in file0.readlines():
   print line
file0.close()
This example code copies a file and outputs it in a different name.
inf = open("python.txt","r")
outf = open("python.py","w")
while line:
   outf.write(line)
   line = inf.readline()
print "python.txt has been copied into python.py."
inf.close()
outf.close()
The following is an application of the above. You can modify the content of an existent file by a code:
import os,time
test = open("test.py","r")
outf1 = open("test.tmp","w")
header = "Test for %s " %time.ctime(time.time())
# Add a line
outf1.write(header+"\n\n")
lines = test.readlines()
for i in range(2,len(lines)):
   outf1.write(lines[i])
outf1.close
test.close()

# Changing the file names.
os.rename("test.py","test.bak")
os.rename("test.tmp","test.txt")
os.remove("test.bak")
This is a typical example to make an output file of your calculation.
#!/usr/bin/python
from numpy import *
from math import *
outf = open("out.d","w")
x=0.0
for i in range(1,1000,1):
   y=math.log1p(x) #math.log1p is the natural log.
   outf.write(str(x)+" "))
   outf.write(str(y)+"\n")
   x+=0.1
outf.close()



Back to Electronics Page

Back to Hiro's Physics Main