0% found this document useful (0 votes)
2 views13 pages

File Handling

The document provides a comprehensive guide on file handling in Python, covering various methods to read from and write to text and binary files. It explains functions such as read(), readline(), readlines(), write(), and their usage in different modes like 'r', 'w', 'a', and 'rb'. Additionally, it includes examples of using the pickle module for serialization and deserialization of data structures.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views13 pages

File Handling

The document provides a comprehensive guide on file handling in Python, covering various methods to read from and write to text and binary files. It explains functions such as read(), readline(), readlines(), write(), and their usage in different modes like 'r', 'w', 'a', and 'rb'. Additionally, it includes examples of using the pickle module for serialization and deserialization of data structures.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

File Handling

#to use read function first you have to create a text file ,write some lines in notepad and save it
#If text file is saved in python main module(installation) path
'''f=open("Demo.txt")
print(f.read())
print("reading lines")'''
#OR use variable a for read fuction
'''f=open("Demo.txt", "r")
a=f.read()
print(a)
print("reading lines")'''

#If text file is saved in any other location like desktop(copy and paste path between quotes)
# use raw(r)mode in starting of path before quotes or \\ to read the file
f=open(r"C:\Users\BABA PC\Desktop\Demo.txt", "r")
print(f.read())
print("Reading lines")
# ORuse this \\
'''f=open("C:\\Users\\BABA PC\\Desktop\\Demo.txt", "r")
print(f.read())
print("Reading lines")'''

#4. type no. of characters which you want to read in read() function
# type function is used only if you are using any variable to print the file handle
'''f=open("Demo.txt", "r")
a=f.read(50)
print(a)
print("Reading characters")
print("type=", type(a))'''

# readline() function read only one line of any paragraph


'''f=open("hello.txt", "r")
a=f.readline()
print(a)
print("Reading only one line")
print("type=", type(a))'''

# if you want to read one line after oneline use readline() function with print function
'''f=open("hello.txt", "r")
a=f.readline()
print(a)
a=f.readline()
print(a)
a=f.readline()
print(a)
print("Reading only one line after one line")
print("type=", type(a))'''

# if you want to read one line after oneline and each line has some specific
# characters use readline(no. of characters) function with print function
'''f=open("Demo.txt", "r")
a=f.readline(6)
print(a)
a=f.readline(8)
print(a)
a=f.readline(10)
print(a)
print("Reading only one line after one line with define no. of characters in function")
print("type=", type(a))'''

# readlines() function return the whole paragraph as a list with each line ends with \n
'''f=open("Demo.txt", "r")
a=f.readlines()
print(a)
print("Reading lines")
print("type=", type(a))'''

# if we want to print all the lines without /n in each line as list use for loop
'''f=open("Demo.txt", "r")
a=f.readlines()
for i in a:
print(i)
print("Reading lines")
print("type=", type(a))'''

# Use of write() function, save your python file in computer not pendrive
# If your text file is not present it will create text file
#Text file will be created in that place where this file saved
# This code will not write any text in the file because close() function is not used
'''f=open("krishna.txt", "w")
f.write("computer science")'''
# This code will write data in the file by close() function
'''f=open("krishna.txt", "w")
f.write("Computer Science with Python")
f.close()
print("Writing Lines in text file")
print("type=", type(f))'''

# if you dont want to write close() function use with() function


'''with open("akash.txt", "w") as f:
f.write("welcome to the python programing")
print("writing line")'''

# If you want to type another text in the place of previous text use this code
#But you previous text will be removed and the new text will show on that place
'''f=open("krishna.txt", "w")
f.write("Welcome to Python")
f.close()
print("Writing Lines in text file")
print("type=", type(f))'''

# If you want to write another line use this code with \n in the starting of text
# If you will not use \n before text then another line text will show in the same 1st line
'''f=open("anshul.txt", "w")
f.write("\nComputer Science with Python")
f.write("\nHello welcome to the python")
f.write("\nCoding in Python")
f.write("\npython is programing language")
f.close()
print("Writing Lines in text file")
print("type=", type(f))'''

# if you want to write more then on line in one function use writelines()
# this function will work in string, list and tuple
'''f=open("nitin.txt", "w")
list=['computer science\n', 'maths\n', 'english\n','physics']
f.writelines(list)
f.close()
print("Writing Lines in text file")
print("type=", type(f))'''

# OR use tuple
'''f=open("nitin.txt", "w")
t=('computer science\n', 'sst\n', 'english\n','python')
f.writelines(t)
f.close()
print("Writing Lines in text file")
print("type=", type(f))'''

# sum programe in file


'''f=open("sumwrite.txt", "a")
a=int(input("enter 1st number"))
b=int(input("enter 2nd number"))
c=a+b
f.write('A= '+str(a))
f.write('\tB= '+str(b))
f.write('\tAddition= '+str(c)+ '\n\n')
f.close()'''

# use of r+ mode, in this mode file pointer is at the begining of the file
'''f=open("demo.txt", "r+")
print(f.read())
f.write("ABC")
f.close()'''

# OR r+ but this last read () will not work because file pointer is in the last of line
# so pointer can not read backword line
'''f=open("Demo.txt", "r+")
print(f.read())
f.write("ABC")
print(f.read())
f.close()'''
# use seek() function after write () to move the pointer at begining of line
# Now it can easily read() the data then write() the data then again read the previous line
'''f=open("demo.txt", "r+")
print(f.read())
f.write("ABC")
f.seek(0)
print(f.read())
f.close()'''

# After read() use seek(5) function to move the pointer at 5th position of line
# Now write some data then again use seek(0) and the read() whole data
'''f=open("demo.txt", "r+")
print(f.read())
f.seek(5)
f.write("BABA INTERNATIONAL SCHOOL")
f.seek(0)
print(f.read())
f.close()'''

# Use tell() function to know the pointer current poition after reading data
'''f=open("Akash.txt", "r")
print("Initially file pointer position is at:",f.tell())
print("It will read 5 bytes:", f.read())
print("After reading file pointer position is at:",f.tell())
print("reading data")'''

# Use tell() function to know the pointer current poition after writing data
'''f=open("Akassh.txt", "w")
f.write("Python Programing")
print("After writing file pointer position is at:",f.tell())
print("writing data")
f.close()'''

# use of W+ mode
'''f=open("Akash.txt", "w+")
f.write("Welcome to Python")
f.seek(0)
print(f.read())
f.close()
print("Writing Lines in text file")
print("reading data")
print("type=", type(f))'''

# use of a+ mode
'''f=open("Akash.txt", "a+")
f.write("\nWelcome to Python")
f.seek(0)
print(f.read())
f.close()
print("Writing Lines in text file")
print("reading data")
print("type=", type(f))'''

# Standard Input/Output
# sys.stdin.read()
#sys.stdin.write()
#sys.stderr.write()
'''import sys
sys.stdout.write("Enter any value")
a=int(sys.stdin.readline())
sys.stdout.write("Enter any value")
b=int(sys.stdin.readline())
if a==0:
sys.stderr.write("Can't devide the numbers")
elif b==0:
sys.stderr.write("Can't devide the numbers")
else:
sys.stdout.write("Division")'''

# Read the text file by sys module (standard I/O)


'''import sys
sys.stdout.write("Enter the file name=")
file=sys.stdin.readline()
f=open(file.strip(),"r")
while True:
ch=f.read(1)
if ch==' ':
sys.stderr.write("now pointer reached at the end of file....")
break
else:
print(ch, end=' ')
f.close()'''

# use of strip () function and \n in the error


'''import sys
sys.stdout.write("Enter the file name=")
file=sys.stdin.readline()
f=open(file,"r")
while True:
ch=f.read(1)
if ch==' ':
sys.stderr.write("now pointer reached at the end of file....")
break
else:
print(ch, end=' ')
f.close()'''

# Absolule Path C:\Users\BABA PC\Desktop\Folder1\Folder 2\File1.txt


# Now we create folder 1 then create folder 2 inside folder 1 on desktop
# Now create a text file with some data in the last(folder 2)
# save the python file in folder 1
f=open(r'C:\Users\BABA PC\Desktop\Folder1\Folder 2\file1.txt', 'r')
print(f.read())
print("reading lines")

# Relative Path
# Now we create folder 1 then create folder 2 inside folder 1 on desktop
# Now create a text file with some data in the last(folder 2)
# save the python file in folder 1
f=open(r'.\Folder 2\file1.txt', 'r')
print(f.read())
print("reading lines")

# Relative Path with two dots..


# create a folder on desktop and save the text file in this
f=open(r'..\hello\file2.txt', 'r')
print(f.read())
print("reading lines")

# Binary files using pickling and unpickling


#Pickling refers to the process of converting the structure of
#(List, Dictionary) to a byte stream before writing in file
# Unpickling is process of converting byte stream back to original structure
# we can write the data in binary files by dump() function
#pickle.dump(structure,file object))
#structure=pickle.load(file object)
# we can read the data from binary file by load() function
'''import pickle
def abc():
f=open("Binary record.dat", 'wb')
list=['Comp. science', 'Maths', 'English', 'Physics', 'Chemistry']
pickle.dump(list,f)
f.close()
abc()
print("Data written in file succesfully...............")'''

# Write and read data from Binary files.


'''import pickle
def write():
f=open("Binaryw.dat", "wb")
list=['Comp. science', 'Maths', 'English', 'Physics', 'Chemistry','sst']
pickle.dump(list,f)
f.close()

def read():
f=open("Binaryw.dat", "rb")
list=pickle.load(f)
print(list)
f.close()
print("Data written in file succesfully...............")
write()
print("Reading data....................")
read()'''

# Read and write data(List and Dictionary) in Binary file


'''import pickle
def write():
f=open("Binary file.dat", "wb")
list=['Comp. science', 'Maths', 'English', 'Phy.', 'Chem.', 'Bio.', 'Eco.']
dict={'Comp' :100, 'Math' : 98, 'Eng' : 95, 'Phy' : 79, 'chem' : 80, 'Bio': 75, 'Eco': 89}
pickle.dump(list,f)
pickle.dump(dict,f)
f.close()

def read():
f=open("Binary file.dat", "rb")
list=pickle.load(f)
dict=pickle.load(f)
print(list)
print(dict)
f.close()
print("Data written in file succesfully...............")
print("Reading data....................")
write()
read()'''

# Read and write data without using def(write): and def(read): function
'''import pickle
f=open("Binarynew.dat", 'wb')
list=['Comp. science', 'Maths', 'English', 'Phy.', 'Chem.', 'Bio.', 'Eco.']
dict={'Comp' :100, 'Math' : 95, 'Eng' : 98, 'Phy' : 82, 'chem' : 84, 'Bio': 80, 'Eco': 95}
pickle.dump(list,f)
pickle.dump(dict,f)
f.close()
print("Data written in file succesfully...............")
f=open("Binarynew.dat", "rb")
list=pickle.load(f)
dict=pickle.load(f)
print(list)
print(dict)
f.close()
print("Reading data....................")'''

#using append mode


'''import pickle
f=open("Binarynew.dat", 'ab')
list=['Comp. science', 'Maths', 'English', 'Phy.', 'Chem.', 'Bio.', 'Eco.']
dict={'Comp' :100, 'Math' : 95, 'Eng' : 98, 'Phy' : 82, 'chem' : 84, 'Bio': 80, 'Eco': 95}
pickle.dump(list,f)
pickle.dump(dict,f)
f.close()
print("Data written in file succesfully...............")
f=open("Binarynew.dat", "rb")
list=pickle.load(f)
dict=pickle.load(f)
print(list)
print(dict)
f.close()
print("Reading data....................")'''

#nested list in binary file


'''import pickle
def write():
f=open("Binarycam.dat", "wb")
a=[ ]
while True:
rno=int(input("enter the roll no : "))
name=input("enter the name : ")
marks=int(input("enter the marks : "))
b=[ rno,name,marks]
a.append(b)
ch=input("Do you want to enter more records .. Y/N ")
if ch=='n' :
break
pickle.dump(a,f)
f.close()
def read():
f=open("Binarycam.dat", "rb")
a=pickle.load(f)
print(a)
f.close()
write()
print("records writing successfully.")
read()
print("Reading data....................")'''

#nested list with for loop displayed as sequence with bracket


'''import pickle
def write():
f=open("Binarycam.dat", "wb")
a=[ ]
while True:
rno=int(input("enter the roll no : "))
name=input("enter the name : ")
marks=int(input("enter the marks : "))
b=[ rno,name,marks]
a.append(b)
ch=input("Do you want to enter more records .. Y/N ")
if ch=='n' :
break
pickle.dump(a,f)
f.close()
def read():
f=open("Binarycam.dat", "rb")
c=pickle.load(f)
for i in c :
print(i)
f.close()
write()
print("records writing successfully.")
read()
print("Reading data....................")'''
#nested list with for loop displayed as sequence without bracket
import pickle
def write():
f=open("Binarycam.dat", "wb")
a=[ ]
while True:
rno=int(input("enter the roll no : "))
name=input("enter the name : ")
marks=int(input("enter the marks : "))
b=[ rno,name,marks]
a.append(b)
ch=input("Do you want to enter more records .. Y/N ")
if ch=='n' :
break
pickle.dump(a,f)
f.close()
def read():
f=open("Binarycam.dat", "rb")
c=pickle.load(f)
for i in c :
rno=i[0]
name=i[1]
marks=i[2]
print(rno,name,marks)
f.close()
write()
print("records writing successfully.")
read()
print("Reading data....................")

#using append function


'''import pickle
def write():
f=open("Binarycam.dat", "wb")
a=[ ]
while True:
rno=int(input("enter the roll no : "))
name=input("enter the name : ")
marks=int(input("enter the marks : "))
b=[ rno,name,marks]
a.append(b)
ch=input("Do you want to enter more records .. Y/N ")
if ch=='n' :
break
pickle.dump(a,f)
f.close()
def append():
f=open("Binarycam.dat", "wb")
a=[ ]
while True:
rno=int(input("enter the roll no : "))
name=input("enter the name : ")
marks=int(input("enter the marks : "))
b=[ rno,name,marks]
a.append(b)
ch=input("Do you want to enter more records .. Y/N ")
if ch=='n' :
break
pickle.dump(a,f)
f.close()
def read():
f=open("Binarycam.dat", "rb")
c=pickle.load(f)
for i in c :
rno=i[0]
name=i[1]
marks=i[2]
print(rno,name,marks)
f.close()
write()
print("records writing successfully.")
read()
print("Reading data....................")
append()
print("enter more data..")
read()
print("reading data agian..")'''

#Use of nested dictionary in binary file


'''import pickle
def write():
f=open("Binarycam.dat", "wb")
M={ }
while True:
r,m=eval(input("enter the roll no :, marks: "))
M[r]=m
ch=input("Do you want to enter more records .. Y/N ")
if ch=='n' :
break
pickle.dump(M,f)
f.close()

def append():
print(" do you want to enter more data..")
f=open("Binarycam.dat", "ab")
V={ }
while True:
r,m=eval(input("enter the roll no :, marks: "))
V[r]=m
ch=input("Do you want to enter more records .. Y/N ")
if ch=='n' :
break
pickle.dump(V,f)
print(V)
f.close()

def read():
f=open("Binarycam.dat", "rb")
b=pickle.load(f)
print(b)
f.close()
write()
print("records writing successfully.")
read()
print("Reading data....................")
append()
read()
print("reading data agian..")'''

# CSV file operations:


# The seperator character of CSV files is called delimiter.
# Default delimiter is comma
# Other popular delimiters are (\t), (:), (|) and (;)

You might also like