File Handling – Python Program

Python provides basic functions and methods necessary to manipulate files by default. You can do most of the file manipulation using a file object.

So, today we will cover the file handling in python. Before you can read or write a file, you have to open it using Python’s built-in open() function. This function creates a file object, which would be utilized to call other support methods associated with it. So, in the below program we will create a menu for reading and writing a file. it will be a simple Menu for just reading and writing data.

Note: The text file should be there in the same folder for reading, where you have saved the program file. Also, write the filename with it’s extension for instance ‘demo.txt’.

Below is the output of the program, have a look and try by yourself. If you still cannot figure it out the then click on Continue Reading… for solution.

file_handling

Here is the solution….Analyze the code and remember that this code will not append the data in the existing file and if the file doesn’t exists the it will create a new file to keep data.

sol_file_handling

def menu():
print(“\nMenu:\n1)Read File \n2)Write File”)
x=int(input(“\nEnter your Choice: “))
if x==1:
read()
elif x==2:
write()
else:
print(“\ninappropriate choice”)
menu()

def read():
name=input(“\nEnter filename: “)
file=open(name,’r’)
print(“\n”,file.read())
file.close()
menu()

def write():
name=input(“\nEnter filename: “)
file=open(name,’w’)
data=input(“\nEnter data: \n”)
file.write(data)
file.close()
print(“\nFile created”)
menu()

menu()

Soon I will be posting a dynamic code which allows user to perform file operations like appending, writing, reading, deleting and much more with data.

If you have any queries, more simplified programs or solutions then kindly comment below. Also you can Email me your doubts and queries related to program.

Thank You!

Attachment: File_IO.py

Advertisements

3 thoughts on “File Handling – Python Program

  1. We have this specific feather in vector file format ask in case you needs Think you could possibly check the data sharing web site to check out the proceedings? My spouse and i adored those down a great deal. Many thanks.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s