Pacific-Design.com

    
Home Index

1. Python

2. File

+ Read

Python / File /

#!/usr/bin/python
import os, re

class MyFile():
    def __init__(self, fname="sample.dat", sep=65):
        self.filename = fname
        self.sep = sep
        os.system("clear")
        print "-" * self.sep

    def write_file(self):
        print "--- Writing into %s ---" % self.filename
        print "Filename =", self.filename

        f = open(self.filename, "w")
        f.write("first  column11 column12 column13 column14\n")
        f.write("small line\n")
        f.write("second column21 column22 column23 column24\n")
        f.close()


    def read_file(self):
        print "-" * self.sep
        print "--- Reading from %s ---" % self.filename

        f = open(self.filename)
        for line in f:
            if(re.search("column22", line)):
                print "column22 exist in =", line,

            if(re.match("small line", line)):
                print "small line exits =", line,

        f.close()

    def split_lines(self):
        print "-" * self.sep
        print "--- Splitting Lines of %s ---" % self.filename

        f = open(self.filename)
        for line in f:

            try:
                entries = re.split(" ", line)
                print entries[0],
                print entries[1],
                print entries[3]
            except:
                print "Exeption: Could not parse Three Values from line!"

        f.close()
        print "-" * self.sep

if __name__ == "__main__":
    mf = MyFile()
    mf.write_file()
    mf.read_file()
    mf.split_lines()