Thursday, November 3, 2011

Python File Operation

Python File Operation:
The below is the script to help to learn about the file read, write operation.
Script will ask operation from the user and do the operation accordingly.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import properties
from properties import filePath
# Program is about read and write operation
# Need to write the file and specify the Name of the file and reading the file.

def writeFile(filename,content):
    f=open(filename,"w")
    f.write(content)
    f.close()

def readfile(filename):
    f=open(filename,"r")
    text=f.read()
    f.close()
    print text


def print_menu():
    print '========================'
    print 'Select any one operation'
    print '1. Write the file'
    print '2. Read the file '
    print '4. exit'
    print
menu_choice = 0
print_menu()
while True:
    menu_choice = input("Type in a number (1-3): ")
    if menu_choice==1:
        print 'Enter the text do you want to write in to the file:'
        filename = raw_input('Enter the name of the file:')
        print 'Next Step ..'
        cont = raw_input('Enter the text')
        writeFile(filePath+filename.rstrip('\n\r '),cont)
    elif menu_choice==2:
        print 'The content of the file is :'
        readfile(filePath+filename.rstrip('\n\r '))
    elif menu_choice==3:
        select = raw_input('You selected to exit yes or no ?')
        try:
            if select.rstrip('\n\r ') == "yes":
                print 'Good bye'
                break
            else:
                print_menu()
        except ValueError:
            print "That was not a Charector ."

No comments:

Post a Comment