Sunday, April 1, 2012

Python File Read operations

Open and read file from within the Python program as a single string using 'read'



import sys
import os
import string

def file_read(file):
      rfile = file.read()
      print rfile
      file = file_read(open('readme.txt', 'r'))

We can also use 
Readlines - as list of strings
Readline - reads only a single line

Read file from command line
Command line arguments lists as string with sys.argv’
import sys
import os
import string

def file_read(file):
      rfile = file.read()
      print rfile
                
if len(sys.argv) == 1:
   file_read(sys.stdin)
else:
   file_read(open(sys.argv[1], 'r'))




No comments: