FILE HANDLING IN PYTHON
File contains information. These files are 2 types and they are as follows
- Text file
- Binary File
Now these files are explained as follows:
- TEXT FILE:
It contains alphabets, digits, symbols.
- BINARY FILE:
In binary file data in the form of 1’s and 0’s .Thee are image, audio, video files.
STEPS TO WORK A FILE:
- Open a file
- Perform operation
- Close the file
EXAMPLE PROGRAMS:
- Write a program to write a contain in a file
f=open(“abc.text”,”w”)
f.write(“pts/n Vijayawada”)
print(“Write operation completed successfully”)
f.close()
For writing a file mode of operation is optional.
- Write a program to read a data from a file:
f=open(“abc.text”,”r”)
data=f.read()
print(data)
f.close()
For read operation file is mandatory “r”.If we open a file in right mode, If file is already existed then open,If file is not existed then create and open.
- Write a program to append the data into a file:
f=open(“abc.text”,”a”)
f.write(“Vijayawada”)
f.close()
- Write a program to read data from given file:
f=open(“abc.text”,”r”)
data=f.readline()
print(data)
f.close()
ReadLine function reads the data in line by line format. Read line function data will be in the form of list.
- In python function can returns multiple values at a type:
def add (a,b) x=a+b y=a-b return x,y a,b=add(2,3) print(a,b)