Python Files Demo

# Python files  demo

# This function writes data into file
def fileWrite():
# fopen=open("sample.txt","w+")
with open("sample.txt","w+") as fopen: # Trying to open a file using 'with' operator. This automatically closes the file.
msg=raw_input('\nEnter the string you want to add to file:\t')
fopen.write(msg)
# fopen.close()

# This function reads data from a file
def fileRead():
fopen=open("sample.txt","r+")
msg=fopen.read() # You can also specify the read(arg) to some numeric value to read till specific line size.
print '\nCharacters read from the file: ',msg
fopen.close()

# This function will append data to existing file
def fileAppend():
fopen=open("sample.txt","a+")
msg=raw_input('\n Enter the string you want to append: ')
fopen.write(msg)
# Reading characters from file after appending
str=fopen.read()
print str

# This function splits words in a file & also counts # of words
def fileSplit():
with open("sample.txt","r+") as fobj:
data=fobj.read()
count=0
for i in data:
word=data.split()
print word
print 'Word count is:',data.count(' ')+1 # This function counts number of words in file

print '\n *** This program demonstrates various operations on Files****'
print '\n 1. Write to a file \n 2. Read from file \n 3. Append data to file \n 4. Word count in file'
option=input('Enter the option you want to perform:')

if option==1:
print '***Write() will append the data to mentioned file (or) will create a new file ***'
fileWrite()

elif option==2:
print '\n *** Read() function will try to read data from existing file***'
fileRead()

elif option==3:
print '\n *** APpend() function will append data to mentioned file (or) create a new file if file doesn\'t exist'
fileAppend()

elif option==4:
print '\n ****Counting Number of words in file ****'
fileSplit()

else:
print 'Your option was not right'

# Output:



0 Comments:

Post a Comment



Older Post Home