Sunday, September 13, 2009

Print file content to output - Python


Required: Write a python program to print the content of a file to output (same as Linux/UNIX cat command do)

Way1: Using file.read file object in python

import sys,os.path

if len(sys.argv) < 2:
print 'No file specified'
sys.exit()
else:
try:
f = open(sys.argv[1], 'r')
print f.read(),
f.close()
except IOError:
print "File" + sys.argv[1] + "does not exist."


Execute it this way: To print the contents of file.txt to the output.

$ python cat-read.py file.txt


Way2: Another similar python program using file.readline

import sys

def readfile(fname):
f = file(fname)
while True:
line = f.readline()
if len(line) == 0:
break
print line.strip() #Avoid strip: print line,
f.close()

if len(sys.argv) < 2:
print 'No file specified'
sys.exit()
else:
readfile(sys.argv[1])


Read about python file()
In python 3.0 file() is removed.

Related concepts:

0 Comments: