0% found this document useful (0 votes)
0 views8 pages

14 File Handling Basics

The document explains file handling in Python, including types of files (text and binary), file operations (open, read/write, close), and various modes for opening files. It provides examples of writing and reading data, as well as methods to manipulate file pointers. Additionally, it covers how to copy data between files and modify file contents using seek and tell methods.

Uploaded by

msuryarukmini
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)
0 views8 pages

14 File Handling Basics

The document explains file handling in Python, including types of files (text and binary), file operations (open, read/write, close), and various modes for opening files. It provides examples of writing and reading data, as well as methods to manipulate file pointers. Additionally, it covers how to copy data between files and modify file contents using seek and tell methods.

Uploaded by

msuryarukmini
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/ 8

Files

As the part of programming requirement, we have to store our data


permanently for future purpose. For this requirement we should go for files.
File is a name location on disk to store related information. It is used to
permanently store data in a non-volatile memory.
File types: -
In Python, a file is categorized as either text or binary files.
Text files are structured as a sequence of characters. Each line is
terminated with a special character, called EOL or End Of Line character.
A binary file is any type of file that is not a text file. Binary files are used to
create non-text files like image or exe files.

In Python, a file operations are:


1. Open a file
2. Read or Write operation
3. Close a file
To open a file:
Before performing any operation (like read or write) on the file, first we have
to open that the file. For this we should use Python’s inbuilt function open().
But at the time of open, we have to specify mode, which represents the
purpose of opening file
Syntax:
fileobject=open("filename",'mode')
Ex:
f=open("data",'w')
f=open("d:/gangadhar/abc.txt",'a')

Python File modes: -


r: - Open an existing file for read operation. The file pointer is positioned at the
beginning of the file. This is default mode. If the specified file does not exist
then we will get FileNotFoundError.
w: - Opens a file for writing only. It creates a new file if it does not exist. If the
file is exist then it overrides the file.
a: - Open a file for appending. The file pointer at the end of the file if the file
exists. If the file does not exist, it creates a new file for writing.
Note: - All the above modes are applicable for text files. If the above modes
suffixed with ‘b’ then these represents binary files.
Ex: rb,wb,ab,r+b,w+b,a+b,xb

Closing a file:
After completing our operations on the file, it is highly recommended to close
the file. For this we have to use close() function.
Syntax:
fileobject.close()

Writing data to files: -


write(): - This method writes any string to the file. Syntax:

fileobject.write("string")
Ex:
f=open("test.txt",'w')
f.write("Python")
f.write("Java")
print("Write operation completed")
f.close()
In the above program all lines write in a file as single line. We can use
\n to convert line by line.
Ex:
f=open("test.txt",'w')
f.write("Python \n")
f.write("Java \n")
f.close()
print("Write operation completed")
f.writelines(list of lines): - To write multiple lines at one time.
Ex:
f=open("test.txt",'w')
l=["gangadhar","lokesh","rajesh","lohit"]
f.writelines(l)
f.close()
print("Write operation completed")

Ex: To write multiple lines using list


f=open("test.txt",'w')
l=["gangadhar \n","lokesh \n","rajesh
\n","lohit \n"] f.writelines(l)
f.close()
print("Write operation completed")

Ex: To write multiple lines using tuple


f=open("test.txt",'w')
t=("gangadhar \n","lokesh \n","rajesh
\n","lohit \n") f.writelines(t)
f.close()
print("Write operation completed")

Ex: To write multiple lines using set


f=open("test.txt",'w')
s={"gangadhar \n","lokesh \n","rajesh
\n","lohit \n"} f.writelines(s)
f.close()
print("Write operation completed")

Ex: Write some data into the file.


File name pass by dynamic input, data entered as dynamic.
fname=input("Enter file name:")
f=open("e:\\gangadhar\\"+fname,'w')
data=input("Enter your data:")
f.write(data)
f.close()
print("Write operation completed")

Reading data from files:


read(): - This method reads total data from the file.
Syntax:
fileobject.read()

Ex:
f=open("test.txt",'r')
print(f.read())
f.close()

read(n): - To read n characters from file


Syntax:
fileobject.read(n)
Here, passed parameter is the number of bytes to be read from the opened
file. This method starts from the beginning of the file.

Ex: To read required number of bytes


f.open("test.txt",'r')
print(f.read(10))
f.close()

readline(): - To read only one line.


Ex:
f=open("test.txt",'r')
line=f.readline()
print(line)
line=f.readline()
print(line)
f.close()

readline method by default provide new line at the end of the line. That’s
every time two lines created. To overcome the problem we can use end
attribute in print statement.
Ex:
f=open("test.txt",'r')
line=f.readline()
print(line,end='')
line=f.readline()
print(line, end='')
f.close()

readlines(): - To read all the lines into list.


Ex:
f=open("test.txt",'r')
print(f.readlines())
f.close()
#output will be in form list

Ex:
f=open("test.txt",'r')
lines=f.readlines()
for line in lines:
print(line)
f.close()

Ex:
f=open("test.txt")
data=f.read(3)
print(data)
print(f.readline())
print(f.read(4))
f.close()

Ex: Write a python program which produces its own source code as its
output

f=input("Enter file name : ")


x=open(f)
for i in x :
print(i)

Ex: Write data in one file to another file


f1=open("input.txt")
f2=open("output.txt","w")
f2.write(f1.read())
f1.close()
f2.close()
print("Data copied from one file to another file successfully")

File positions:
tell(): - To return current position of the cursor. File pointer at the starting
position it returns 0.

Ex:
f=open("abc.txt",'r')
pos=f.tell()
print("Current position=",pos)
str=f.read(5)
print(str)
pos=f.tell()
print("Current position=",pos)
str=f.read(5)
print(str)
pos=f.tell()
print("Current position=",pos)

seek(offset,from): - This method move the cursor (file pointer) to specified


location.
Syntax:
fileobject.seek(offset,fromwhere)
offset represents the number of posions.
The allowed values for 2nd attribute (from where) are:
0From beginning of file (Default value).
1From current position.
2From end of the file.
Note: Python 2 supports all 3 values but Python 3 supports only zero.

Ex:
f=open("test.txt",'r')
pos=f.tell()
print("Current position=",pos)
f.seek(10,0)
str=f.read(5)
print(str)
pos=f.tell()
print("Current position=",pos)
f.seek(5,0)
str=f.read(5)
print(str)
pos=f.tell()
print("Current position=",pos)
Ex:
data="All Students are normal"
f=open("abc.txt","w")
f.write(data)
with open("abc.txt","r+") as f:
text=f.read()
print(text)
print("Current position=",f.tell())
f.seek(17)
print("The Current position=",f.tell())
f.write("Gems!!!")
f.seek(0)
text=f.read()
print("Data after modification")
print(text)

Ex:
data="All Students are Gems!!!"
f=open("abc.txt","w")
f.write(data)
with open("abc.txt","r+") as f:
f.seek(1000)
f.write("Gangadhar")
print(f.tell())

You might also like