#!/usr/bin/python3
''' Working with a file. A shortened version of the file is available from

www.py4e.com/code3/mbox-short.txt
'''
fhand = open('/home/marat/python/py4e/mbox-short.txt')
count = 0
for line in fhand:
    count +=1
print(count)
print('!!!!!!!!!!!!!!!!') 
#_________________________
fhand = open('/home/marat/python/py4e/mbox-short.txt')
inp = fhand.read()
print(len(inp))
print(inp[:161])
print('!!!!!!!!!!!!!!')
#######################

fhand = open('/home/marat/python/py4e/mbox-short.txt')
count = 0
for line in fhand:
    line = line.rstrip() # to remove extra newline character "\n" from a line
    if line.startswith('From:'):
        print(line)
        count +=1
print(count)        
print("################")

################################
fhand = open('/home/marat/python/py4e/mbox-short.txt')
count = 0
for line in fhand:
    line = line.rstrip()
    if not line.startswith('Received: FROM'):
        continue
    print(line)
    count += 1
print(count)
print('############')
########################
fhand = open('/home/marat/python/py4e/mbox-short.txt')
count = 0
for line in fhand:
    line = line.rstrip()
    if line.find('@uct.ac.za') == -1:
        continue
    print(line)
    count +=1
print(count)
print('##############')
##########################


fname = input('Enter the file name: ')
search = input('Type the searching word: ')
try:
    fhand = open(fname)
except:
    print('File cannot be opened: ', fname)
    exit()
count = 0
for line in fhand:
    line = line.rstrip()
    if line.startswith(search):
        print(line)
        count += 1
print('There were {} {} lines in the {} file'.format(count, search, fname))
###############################
# Writing in the file!!!
#!/usr/bin/python3

fname = input('Enter the file name: ')
fhand = open(fname)
fout = open('out.txt', 'w')
count = 0
for line in fhand:
    line = line.rstrip()
    if not line.startswith('From:'):
        continue
    count +=1
    #print('{}, {}'.format(line, count))
    fout.write('{}, {}\n'.format(line, count))
print(fout)
fout.close()
fhand = open('out.txt')
for line in fhand:
    line = line.rstrip()
    print(line)

