Python I/O

It is very likely that programs we write will need input as they run and/or will generate output as they run. Understanding how input and output work is called I/O for short. Input and output are mainly done through the command line or through files. For files this is called reading and writing. Here we will discuss input from the terminal, printing, writing to file and reading from a file.

Input

The simplest way to get input to your program in python is to use the input() function

x = input("Enter the value of x here:")

This will print the message in the quotes (called the prompt) to the screen and then x will be set to whatever you type before hitting enter. Note that x will always be a string, if you want a different variable type you will have to cast x to what you want. Also note you should probably check what is passed since if you expect a work and someone passes a number that can mess up the rest of your program.

Print

Output to the screen is done with the print() function. Any type of variable can be passed to print and it will follow certain rules on how it is printed which can be adjusted.

x=5
y="number is:"
print("The",y,x)

Files

Reading and writing to files requires opening a file and then using read or write methods. Opening a file is done with the open function. The default is to open a file for reading, if one wants to write to the file you have to set the mode to ‘w’. Also the default is that the file will be treated as text, if you want to read or write binary you need the ‘b’ mode. If you read in binary you can pass the number of bytes you want to read to the read() function.

f = open(filename1,mode='r')
words = f.read()
f.close()
f = open(filename2,mode='w')
text="This are the words I want to write to a file"
f.write(text)
f.close()

This will read the contents of filename1 into words. Alternatively one could use f.readline() to read one line from the file, or f.readlines to read all of the lines into a list. In the second part the text will be written into filename2. One common trick is to run these commands in a loop to do thing line by line.

f = open('readfile',mode='r')
for line in f:
cols=line.split()
f.close()
f = open('writefile',mode='w')
for i in range(10):
write(i)
f.close()

More advanced reading and writing can be done with the tell, seek and read methods. f.tell() gives you your current location in the file in bytes. f.seek(N) goes to the N+1 byte in the file and f.read(N) reads N bytes from the file. This gives one complete control on reading the file, but usually one will be fine with just going line by line.

Advanced File Reading

There are a lot of common file types and those often have special functions for reading and writing them. Just google python reader or writer and the file type and you are likely to be able to save yourself a lot of time. One very common file type is called comma separated values (CSV), but it included any file in regular text separated in columns. This type of file can be read using numpy or pandas like this:

import numpy as np
import pandas as pd

data1 = np.loadtxt(“datafile.csv”,delimiter=’, ‘,unpack=False)
x,y,z = np.loadtxt(“datafile.dat”,comments=’#’,unpack=True)
data = pd.read_csv(“datafile.txt”)

A common file type specific to astronomy is called a fits file. Therefore a package specific to astronomy is likely to have have fits reader and writer functions.

import astropy.io as aio

hdul=aio.fits.open(“file.fits”)
hdul.info() #files might contain images or tables both etc.
hdr=hdul[0].header
data=hdul[1].data
cols=hdul[1].columns

#writing an array to a file
n = np.arange(100.0)
hdu = fits.PrimaryHDU(n)
hdu.writeto(‘new2.fits’)

Print this page