Chapter 12: Working with Files

Program 12.1, page no. 498

In [13]:
import sys


mystr = []

print "Enter an interesting string of up to 80 characters: ",
mystr = raw_input()

try:
    fp = open("myfile.txt", "w")
except:
    print "error opening the file..."
    sys.exit()

for i in range(len(mystr)-1, -1, -1):
    fp.write(mystr[i])

fp.close()

try:
    fp = open("myfile.txt", "r")
except:
    print "error opening the file..."

print "the data read from the file is: "
while(True):
    c = fp.read(1)
    if not c:
        break
    print c,
fp.close()
Enter an interesting string of up to 80 characters: Too many cooks spoil the broth.
 the data read from the file is: 
. h t o r b   e h t   l i o p s   s k o o c   y n a m   o o T

Program 12.2, page no. 502

In [3]:
proverbs = ["Many a mickle makes a muckle.\n",
            "Too many cooks spoil the broth.\n",
            "He who laughs last didn't get the joke in the first place.\n"]
 
more = []

try:
    fp = open("myfile.txt", "w") 
except:
    print "error opening the file..."
for proverb in proverbs:
    fp.write(proverb)
fp.close()
 
fp = open("myfile.txt", "a")
 
print "Enter proverbs of up to 80 characters (separated by '.') or press Enter to end:\n",
string = raw_input().split('.')


for str in string:
    fp.write(str+"\n")
fp.close()

fp = open("myfile.txt", "r")
print "The proverbs in the file are: \n"
while(True):
    line = fp.readline()
    if not line:
        break
    print line
fp.close()
Enter proverbs of up to 80 characters (separated by '.') or press Enter to end:
Every dog has his day. Least said, soonest mended. A stitch in time saves nine. Waste not, want not.
The proverbs in the file are: 

Many a mickle makes a muckle.

Too many cooks spoil the broth.

He who laughs last didn't get the joke in the first place.

Every dog has his day

 Least said, soonest mended

 A stitch in time saves nine

 Waste not, want not



Program 12.3, page no. 507

In [4]:
import sys

num1 = 234567
num2 = 345123
num3 = 789234

ival = []

try:
    fp = open("myfile.txt", "w")
except:
    print "Error opening file for writing. Program terminated.\n"
    sys.exit()

fp.write("%6d %6d %6d" %(num1, num2, num3))
fp.close()
print "%6ld %6ld %6ld" %(num1, num2, num3)

try: 
    fp = open("myfile.txt", "r")
except:
    print "Error opening file for reading. Program terminated.\n"
    sys.exit()

line = fp.readline()
line_split = line.split(" ")
num4 = int(line_split[0])
num5 = int(line_split[1])
num6 = int(line_split[2])
print "%6ld %6ld %6ld " %(num4, num5, num6)
fp.close

fp = open("myfile.txt", "r")
line = fp.readline()
line_join = "".join(line_split)
ival.append(int(line_join[0:2]))
ival.append(int(line_join[2:5]))
ival.append(int(line_join[5:8]))
ival.append(int(line_join[8:11]))
ival.append(int(line_join[11:13]))
ival.append(int(line_join[13:15]))
fnum = (float(line_join[15:]))

for i in range(len(ival)):
    print "%sival[%d] = %d" %(("\n\t" if i == 4 else "\t"), i, ival[i]),
print "\nfnum = %f " %fnum
234567 345123 789234
234567 345123 789234 
	ival[0] = 23 	ival[1] = 456 	ival[2] = 734 	ival[3] = 512 
	ival[4] = 37 	ival[5] = 89 
fnum = 234.000000 

Program 12.4, page no. 514

In [11]:
import math
import sys

MEM_PRIMES = 10
PER_LINE = 8
filename = "myfile.bin"
fp = None
primes = [2, 3, 5]
count = 3

def check(buff, count, n):
    root_N = (1.0 + math.sqrt(n))
    for i in range(0, count):
        if(n % buff[i] == 0):
            return 0
        if(buff[i] > root_N):
            return 1
    return -1

def list_array():
    global primes
    global count
    for j in range(count):
        print "%10lu" %primes[j]
        if(((j + 1) % PER_LINE) == 0):
            print "\n"
    
def list_primes():
    global fp
    global filename
    global count
    global primes
    if(fp):
        try:
            fp = open(filename, "rb")
        except:
            print "Unable to open %s to read primes for output " %filename
            sys,exit()
        while(True):
            line = fp.readline()
            if line:
                list_array()
        print "\n"
        fp.close()
    else:
        list_array()

def write_file():
    global fp
    global filename
    global count
    global primes
    try:
        fp = open(filename, "ab")
    except:
        print "Unable to open %s to append\n" %filename
        sys.exit()
    for prime in primes:
        fp.write(prime+" ")
    fp.close
    count = 0

def is_prime(n):
    global filename
    global fp
    global primes
    global count 
    buff = []
    count = 0
    k = 0
    if(fp):
        try:
            fp = open(filename, "rb")
        except:
            print "Unable to open %s to read. " %g.filename
            sys.exit()
        while(True):
            line = fp.readline()
            if line:
                nums = line.split(" ")
                for num in nums:
                    buff.append(int(num))
                k = check(buff, count, n)
                if(k == 1):
                    fp.close()
                    return True
            else:   
                break
        fp.close()
    return 1 == check(primes, count, n)

trial = primes[count - 1]
num_primes = 3

print "How many primes would you like? ",
total = int(raw_input())
total = 4 if total < 4 else total
print total
while(num_primes < total):
    trial += 2
    if(is_prime(trial)):
        primes.append(trial)
        count += 1
        num_primes += 1
        if(count == MEM_PRIMES):
            write_file()

if(fp and count > 0):
    write_file()
list_primes()

Program 12.5, page no. 523

In [11]:
class Date:
    day = 0
    month = 0
    year = 0
 
class Family:
    dob = Date()
    name = ""
    pa_name = ""
    ma_name = ""

members = []

def get_person():
    while(True):
        temp = Family()
        print "Enter the name of the person: ",
        temp.name = raw_input()
        print "Enter %s's date of birth (day month year): " %temp.name
        temp.dob.day = int(raw_input("Day: "))
        temp.dob.month = int(raw_input("Month: "))
        temp.dob.year = int(raw_input("Year: "))
        print "Who is %s's father? " %temp.name,
        temp.pa_name = raw_input()
        print "Who is %s's mother? " %temp.name,
        temp.ma_name = raw_input()
        print "\nDo you want to enter details of a person (Y or N)? ",
        more = raw_input()
        members.append(temp)
        if(more.lower() == 'n'):
            return

def show_person_data():
    fp = open("myfile.bin", "rb")
    count = 0
    while(True):
        line = fp.readline()
        if line:
            member_data = line.split(",")
            print "%s's father is %s, and mother is %s." %(member_data[0],member_data[4], member_data[5])
            found_relative, relative_info = get_parent_dob(members[count])
            if found_relative:
                print relative_info
            else:
                print "No info on parents available"
        else:
            break
    fp.close()

def get_parent_dob(member):
    parent_info = ""
    found_relative = False
    for parent in members:
        if parent.name == member.pa_name:
            parent_info = parent_info+"Pa was born on %d %d %d" %(parent.dob.day, parent.dob.month, parent.dob.year)
            found_relative = True
        elif parent.name == member.ma_name:
            parent_info = parent_info+" Ma was born on %d %d %d" %(parent.dob.day, parent.dob.month, parent.dob.year)
            found_relative = True
    return found_relative, parent_info


print "Do you want to add details of a person ? (Y/N): ",
more = raw_input()
if more.lower() == 'n':
    import sys
    sys.exit()

get_person()
fp = open("myfile.bin", "wb")
for member in members:
    line = member.name+","+str(member.dob.day)+","+str(member.dob.month)+","+str(member.dob.year)   +","+member.pa_name+","+member.ma_name
    fp.write(line)
    fp.write(",\n")
fp.close()
show_person_data()

Program 12.6, page no. 531

In [11]:
MAXLEN = 50

def listfile():
    fp = open("mypeople.bin", "rb")
    print "The folks recorded in the mypeople.bin file are: "
    while(True):
        line = fp.readline()
        if line:
            print line.split(",")[0], "\t\t\t\t\t", line.split(",")[1]
        else:
            break
    fp.close()

answer = 'y'
fp = open("mypeople.bin", "wb")
while(answer.lower() == 'y'):
    print "Enter a name less than %d characters: " %MAXLEN,
    name = raw_input()
    print "Enter the age of %s: " %name,
    age = int(raw_input())
    length = len(name)
    line = name+","+str(age)
    fp.write(line)
    fp.write(" \n")
    print "Do you want to enter another(y or n)? ",
    answer = raw_input()
fp.close()
listfile()

Program 12.7, page no. 545

In [11]:
class Record:
    name = ""
    age = 0

records = []

def write_file(mode):
    global filename
    fp = open(filename, mode)
    more = 'y'
    while(more == 'y'):
        print "Enter name less than 30 characters: ",
        name = raw_input()
        name = "%30s" %name
        print "Enter age of ", name
        age = raw_input()
        age = "%3s" %age
        line = name+","+age
        fp.write(line)
        fp.write(" \n")
        print "Do you want to enter another (y/n)? ",
        more = raw_input()
    fp.close()
    return

def list_file():
    global filename
    fp = open(filename, "rb")
    print "The folks recorded in the mypeople.bin file are: "
    while(True):
        line = fp.readline()
        if line:
            line_split = line.split(",")
            print line_split[0].strip(), "\t\t\t\t\t", line_split[1]
        else:
            break
    fp.close()

def remove(fname):
    import os
    os.remove(fname)

def update_file():
    global filename
    new_record = Record()
    fp = open(filename, "rb+")
    print "Enter name to be updated: ",
    update_name = raw_input()
    update_name = "%30s"%update_name
    while(True):
        old_pos = fp.tell()
        old_line = fp.readline()
        if old_line:
            if old_line.split(",")[0] == update_name:
                print "You can now enter new name and age for ", update_name
                print "Enter name less than 30 charactesrs: ",
                new_name = raw_input()
                new_name = "%30s"%new_name
                print "Enter age for ", new_name
                new_age = raw_input()
                new_age = "%3s"%new_age
                pos = fp.tell()
                fp.seek(old_pos)
                new_line = new_name+","+new_age+" \n"
                new_line = old_line.replace(old_line, new_line)
                fp.write(new_line)
        else:
            break
    fp.close()
    
filename = "my-people.bin"
answer = 'q'
while(True):
    print "Choose from the following options: "
    print "To list the file contents enter L"
    print "To create a new file enter C "
    print "To add new records enter A"
    print "To update existing records enter U"
    print "To delete the file enter D"
    print "To end the program enter Q: ",
    answer = raw_input()
    if answer.upper() == 'L':
        list_file()
    elif answer.upper() == 'C':
        write_file("wb+")
        print "File creation complete."
    elif answer.upper() == 'A':
        write_file("ab+");
        print "File append complete."
    elif answer.upper() == 'U':
        update_file()
    elif answer.upper() == 'D':
        print "Are you sure you want to delete %s (y or n)? ",
        confirm_delete = raw_input()
        if(confirm_delete.lower() == 'y'):
            remove(filename)
    elif answer.upper() == 'Q':
        print "Ending the program. "
        import sys
        sys.exit()
    else:
        print "Invalid selection. Try again."

Program 12.8, page no. 551

In [14]:
import binascii

print "Enter filename: ",
filename = raw_input()

f = open(filename, "r")

for line in f.readlines():
    print (binascii.hexlify(line)),
    print " | ", line

f.close()
Enter filename: myfile.txt
 2e68746f726220656874206c696f707320736b6f6f6320796e616d206f6f54  |  .htorb eht liops skooc ynam ooT