File Handling - 2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Lesson-5/Page-4 Python File Handling

Closing Files :-

An open file is closed by calling function close() in Python otherwise error of data
loss is possible. When we use close() function it breaks the link from the disk so no
any task is possible.

Syntax:-

<file_handeler>.close()

Example :-

myfile.close()

Reading and Writing Files:-

Python provides many function for reading and writing the open filess.

Method Syntax Description


read() <filehandle>.read([n]) Read at most n bytes. If no n is specified
reads the entire file.
Returns the read bytes in the form of a
string.
readline() <filehandle>.readline([n]) Reads a line of input, If n is specified
reads at most n bytes.

readline() <filehandle>.readlines([n]) Read all lines and return them in a


Form of List.

Example :-

# First we create a text file which name is “demo_file.txt”, Its contain is---

Computer is an electronic machine.

Which takes in data & information,


4
Process it and gives the result

According to our requirement

faster then human being.

# Python code for file handling is------(Reading a file and print it)

# Number of bytes(n) is not given

myfile=open('c:\\demo_file.txt',"r")

str=myfile.read()

print(str)

myfile.close()

# Number of bytes(n) is not given and not use”\\”

myfile=open(r'c:\demo_file.txt',"r")
str=myfile.read()
print(str)
myfile.close()

# Number of bytes(n) is given (Reading n bytes and print it)

myfile=open('c:\\demo_file.txt',"r")
str=myfile.read(10)
print(str)
myfile.close()
5

You might also like