Alphalearningschool
        

<<< Prev

Next >>>

Up
Python Files IO

Most important topic in python this will be use in real world project. Till now we are displaying output only in consol same as we are taking input from consol only but in python file IO we will take input and get output in file(Like txt, doc etc..)

For this file IO python has provide a so many by default function for example open () use for open a file read () is use for read a file like so many other function are there in python let we see step by step.

In file handling there are some different method are available.

1

r

It open file to read only .it will throw error if file are not exist.

2

rb

Open the file and reading in binary formate.

3

r+

Open file for the both the purpose reading and writing.

4

rb+

Open file reading , writing the binary file.

5

w

Open file for written purpose only.

6

wb

open file written binary format.

7

w+

Same as r+ Mode. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

8

wb+

Open file written , read the binary format.

9

a

Open file for appending.

10

ab

Open file for appending in binary format.

11

a+

Open file for appending , reading as well as writing.

 

12

ab+

Open file for reading and appending binary file.

 

Ex.1
f2=open("demo.txt","r")
if f2:
    print("Demo file is open")
    f2.close()
print("------------------")
f=open("demo.txt")# This will read specific name of the file
f1=open("demo.txt","r")
#print(f.read())
#print(f1.read())
#print(f.readline())
print(f.read(9)) #Reading data from file in particular index

#Step by step you should uncomment the python code you will get the out put for that

O/P
Demo file is open
------------------
This pyth

 

Ex.2
#Write the file
file=open("demo.txt","a")
file.write("Hello Welcome to python Tutorial") #After run you have to check your .txt file.
#Create new file
file_new=open("index.txt","x") #Here you can give path wherever you want to create a file
print(file_new)
if file_new:
    print("File is created")

O/P
<_io.TextIOWrapper name='index.txt' mode='x' encoding='cp1252'>
File is created

 

Ex.3
#Now we use with statement in file
with open("demo.txt","r") as w:
    c=w.read();
    print(c)

file=open("demo.txt","r")
print(file.tell()); #without reading file pointer
print(file.read())
print(file.tell())#After reading the file pointer


O/p
This python tutorial is made by Alphalearningschool.com

0
This python tutorial is made by Alphalearningschool.com

57

 

Ex.4
#Modifying the File Pointer Position
file=open("demo.txt","r")
print(file.read())
print(file.tell())
file.seek(10) # For changing file pointer position we use seek() function
print("After Seek")
print(file.tell())

O/P
This python tutorial is made by Alphalearningschool.com
57
After Seek
10

See the above example you will get idea where to use this function.