Files in Python

 

Explain Files concept in python?

To store data in a computer, we need files. Once we store data in a computer file, we can retrieve it and use it depending upon our requirements.

Advantages of Files

1.  To store data permanently.

2.  To update the file data.

3.  Sharing of data is easily

4.  These are useful to store huge amount of data.

There are two types of files.

1.  Text file

To store the data in the form of characters.

Character data

2.  Binary File

To store the data in the form of bytes.

Character data, Images, Audio files, Video files,…

Opening of a File:-

open() is used to open the file.

Syntax:-

filehandler=open(“Filename”,”Openmode”,”buffering”)

f=open(“myfile.txt”,”w”)

 

filename=name of the while on which the data is stored or the data is retrieved.

File modes

File Open mode

Description

w

To write data into a file. If any data is already present in the file, it would be deleted and the present data will be stored.

r

To read data from the file. The file pointer is pointed in the beginning of the file.

a

To append data to the file. Appending means adding at the end of existing data. If the file does not exist, it will create a new file for writing

w+

To write and read the data of a file. The previous data in the file will be deleted.

r+

To read and write the data of a file. The previous data in the file will not be deleted.

a+

To append data to the file. Appending means adding at the end of existing data. If the file does not exist, it will create a new file for both writing and reading

x

To open the file in exclusive creation mode. If the file exists it shows an error.

The modes in the above table are used for text files. If we want to use them for binary files attach ‘b’ for each mode like wb, rb, ab, w+b, etc.,

 

Buffering is an optional integer value. The default buffer size is used as 4096 or 8192 bytes.

Closing a file:-

By using close() we can close the file. Once a file is opened but not closed, then the data of the file may be corrupted or deleted in some cases.

filehandler.close()

Program to store contents in a file (or) program to create a file

f=open("f:\mcafile.txt","w")

data=input("enter data to store into a file")

f.write(data)

print("1 file created")

f.close()

Output:-

enter data to store into a filethe information stored in mcafile.txt
1 file created

 

Program to read contents from a file

try:

    filename=input("enter file name")

    f=open(filename,"r")

    data=f.read()

    print("The contents in the file are:")

    print(data)

except IOError:

    print("There is no file exists in the system")

finally: 

    f.close()

output:-

enter file namef:\mcafile.txt

The contents in the file are:

this is a file opened in write modethe data is stored at the end of the previous file

 

 

enter file namesample.java
There is no file exists in the system
 

#program to copy the contents of one file into another file

try:

    sfname=input("Enter source file name")

    sf=open(sfname,"r")

except IOError:

    print("Source file does not exist")

else:

    dfname=input("enter destination file name")

    df=open(dfname,"w")

    data=sf.read()

    df.write(data)

    print("1 file copied")     

finally:

    sf.close()

    df.close()

Output:-

Enter source file namef:\special.java
enter destination file namef:\special1.java
1 file copied

 

Enter source file namef:\sample.java
Source file does not exist

 

 

Checking whether a file exists or not

The operating system (os) module has a sub module by the name path that contains a method isfile(). This method can be used to know whether a file that we are opening really exists or not.

import os

os.path.isfile(fname)- if the fname is exists in the given path then it returns true otherwise it returns false.

Program to check whether a file exists or not

import os

fname=input("Enter filename")

if(os.path.isfile(fname)):

    f=open(fname,"r")

    data=f.read()

    print(data)

    f.close()

else:

    print("file does not exists")

Output:

Enter filenamef:\myfile.txt

this is myfile example

 

Enter filenamef:\bharathi.txt

file does not exists

 

Binary files

Binary files handle data in the form of bytes. So, they can be used to read or write text, images, audio or video files. To open a binary file for reading purpose, we can use ‘rb’ mode. Here, b represents binary file and r represent open the file in read mode.

/* copy the content of one file into another file*/

fs=open("d:\\bestpic.JPG","rb")

fd=open("d:\\ammujo.JPG","wb")

byte=fs.read()

fd.write(byte)

fs.close()

fd.close()

print("1 file copied")

 

Output:-

1 file copied

 

seek() and tell() methods

 

tell()-To know the position of the file pointer

seek(offset,fromwhere)- to move the file pointer to another position. Offset represents how many bytes to move. fromwhere represents can be any value like 0,2,69,…

#Program to demonstrate seek methode

f=open("f:\mcafile.txt","w+")

data=input("enter data to store into a file")

f.write(data)

print("1 file created")

#after writing the data into the file the file pointer is placed at the end.

#to read the information from file, you need to place the file pointer at the starting position.

f.seek(0)

data=f.read()

print("the information in the file")

print(data)

f.close()

 

output:-

enter data to store into a filethis is new mca file

1 file created

the information in the file

this is new mca file

 

Comments

Popular posts from this blog

Strings in Python

Tuples in Python

Exception Handling in Python