0% found this document useful (0 votes)
16 views16 pages

Python File Handling Basics

Uploaded by

navyasri04goud
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views16 pages

Python File Handling Basics

Uploaded by

navyasri04goud
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

FILE HANDLING

A file is collection of information. A file is stored permanently on some storage


device called hardisk, pendive, etc.

A file is a document which stores data permanently. We can read and write data
according to the requirement.

When file is created using python programming language it is called


“filehandling”.

Advantages:

 Data is stored permanently.


 Already existing data can be used.
 Large amount of data can be processed easily.

Types of files in python:

1. Text file: normally information written in notepad file is text file. text file
stores information in ASCII or UNICODE.
Each line of text is terminated (ended)with a special character known as
EOL(end of line).which represents new line character, after writing one
sentence if we press enter key from keyboard it is new line character here
enter key works as EOL which represents first line is finished.
In text file if we don’t mention the extension takes .txt extension.
2. Binary files: A binary file contains the information in binary form.
Binary files are difficult to understand. Some of the binary files examples are
audio, video, images etc.
Binary file extension is .dat
3. CSV files: CSV files stores information in tabular format that is in rows and
columns
CSV stands for comma separated values
How to open a text file?

To open a text file we use following syntax:

filevariable=open(“<file path><filename>”,<mode>)

To open a file in python we use two functions

1. open() function

2. with statement

[Link]():

This method is very easy to use. The open () function opens a file, and returns it
to a file variable. it has two arguments [Link] [Link]

filevariable=open(“<file path(optional)><filename>”,<mode>)

1. File name – it consists path, name of the text file

Note: if we don’t mention the path the file is stored in default python folder
where all python programs are stored.

f=open (“[Link]”,”w”)

If we mention the path the file is stored in that particular location

Ex: f=open (“c:\\users\\desktop\\[Link]”,”w”)

Here above file”[Link]” is stored on desktop.

[Link]: - we need to enter mode while opening a file. If we do not provide the
mode, it takes 'r' mode (open for reading in text mode)

Types of modes

“w” mode- creates a new file and we can write new content in that file
f=open(“[Link]”,”w”)
Note:
If the file already exists if we use “w” mode again new file is not created but
the information in that file will be overridden with new content. the old
content will be erased.

“r” mode – it reads data from the file but it does not create a new file. It is
used to read the data from existing file.

 If file is not created and if we use “r” mode it shows

“file not found error”

Ex:

f=open(“[Link]”,”r”)

If file exists it will not display any error.

But where as “w” mode does not show any error it creates new file and writes
new data into it by deleting old data.

“a” mode: It adds new content(information)for existing information in a file.


without deleting the old information.

 It also creates a file if the file does not exist.

Ex:

f=open(“[Link]”,”a”)
2. opening a file using with function

Using with keyword we can create and open a file .statements written under with
will be taken indentation.

Example:

with open ("C:\\Users\\Desktop\\[Link]","w") as fp:

print("file created")

output:

In python shell it prints

On desktop
“[Link]” file is created

python if we don’t give the path the files are stored in


ow folder

=open(“[Link]”,”r”)
Reading data from a file

There are three ways to read data from file

[Link]()

[Link]()

[Link]()

[Link](): read function reads complete all the characters that are present in a a
file

 Read () functions reads data in the form of a string.


 If the value in read function is given it reads only those many characters
 ex: read(n) “reads n characters from the file”
 read(6) “reads 6 characters from the file”
 if “n” value is not given reads complete file.

program1.

f=open("[Link]","r")

x=[Link]()

print(x)

[Link]()

Explanation:

read() function is reading the complete file because the “n” value is not given.
Program2:

f=open("[Link]","r")

x=[Link](20)

print(x)

print(type(x))

[Link]()

Explanation:

In the above program only “20” characters are read because we have given the
“n” values as 20

And read() function returns the string type. so it is printing <class ‘str’>

if there are less characters in a file if give “n” value as big in read()function it does
not displays error but display all characters in a file.

[Link]():

 readline() function reads only a single line.


 If the “n” value in readline() function is given then it reads those many
characters in that particular line.
 After reading all the characters in a particular line it reads the next line
characters.
 readline() function returns the string type. readline () function takes(“\
n”)newline character.
 Program1:
f=open("[Link]","r")
x=[Link]()
print(x)
x=[Link]()
print(x)
print(type(x))

Explanation:

In above program two times we called readline() function

So first time first line data of file is printed Second time second line data of file is
printed

And it returns the “string” type value i.e., <class ‘str’>

There is a gap between the lines because readline() function takes(“\n”)newline


character.

Program2.

f=open("[Link]","r")

x=[Link](15)

print(x)

x=[Link](15)
print(x)

x=[Link](15)

print(x)

explanation:

In readline () function the value(15) is given so it reads specified characters of that


particular line.

Here in the above program it is reading first line 15charcters and next 15
characters and then 15 characters of same line.

[Link]():

Reads all the characters in a file and display the information in the form of a list.

Note:

The difference between read () and readlines()

read() function display the output as a string and readlines()function display the
information in the form of a list.

Program 1.

f=open("[Link]","r")

x=[Link]()

print(x)

print(type(x))
output:

Explanation: the information of a file is displayed in a list


with (“\n”)EOL characters. and the type it returns is <class ‘list’>
How to write data in a file?

There are two methods to write data in a file.

[Link]()

[Link]()

[Link](): this function takes string as input and writes the it into the file.

For displaying data in the new lines we EOL (“\n”).

For storing numeric values we need to convert explicitly to “str” type.

Ex.

f=open("[Link]","w")

[Link]("computer science")

[Link]("\nclass XII")

[Link]()

Note:In [Link] we have written

computer science

class XII

Ex2:

f=open("[Link]","a")

a=eval(input("enter first number"))

b=eval(input("enter second number"))

c=a+b

[Link]("a="+str(a))

[Link]("b="+str(b))
[Link]("\taddition="+str(c))

[Link]()

output:

Note: In file”[Link]” it will be displayed as

a=3b=5 addition=8

[Link]: write lines function is used to writes sequence data types in a file
i.e. is string, list, tuple.

Ex. program to write string, list, tuple using write lines function.

f=open("[Link]","w")

[Link]("CLASS XII")

[Link]("\nICON&SPARK")

#list

list1=["\ncomputer","\nmaths","\nenglish"]

[Link](list1)

#tuple
tuple1=("\nbotony","\nzoology","\nchemistry")

[Link](tuple1)

[Link]()

Note: in the “[Link]” file we see the following output:

CLASS XII

ICON&SPARK

computer

maths

english

botony

zoology

chemistry

How to append data to a file?

Append means to add the data at the end of the file.

If the file does not exist it will create the new file.

If the file exists it will append the data at the end of the file.

we use ”a” mode to append data into the file and append mode uses write() and
writelines() functions.

Ex.

f=open("[Link]","a")

x=["\npython","\nfile","\nhandling"]
[Link](x)

[Link]()

Note : in the file”[Link]” “python”, “file”, “handling” is appended.

output:

CLASS XII

ICON&SPARK

computer

maths

english

botony

zoology

chemistry

python

file

handling

python

file

handling

How to close files?

close() function is used to close the opened file.

A close() function breaks the link of the file variable and the file.
After close() function no task will be performed on that file through file variable.

Ex.

[Link]()

r+ , w+ and a+ modes

“a+”:
“a+” mode is used for both reading and appending .the file pointer is at the end of
the file if the file exists .if the file does not exists the file pointer will be at the
beginning.

Examples:

f=open("[Link]","r+")

[Link]("welcome to python programming")

[Link]()

[Link]("hello world")

[Link]()

[Link]()

Note: in “[Link]” we have the following information

output:

welcome to python programminghello world

Ex 2

f=open("[Link]","w+")

[Link]("computer science")

[Link]()

[Link]("python world")
[Link]()

Note: in “[Link]” we have the following information

Output:

computer sciencepython world

Ex3.

f=open("[Link]","a+")

[Link]("class12")

[Link]()

[Link]()

Note: in “[Link]” we have the following information

Output:

computer sciencepython worldclass12

You might also like