You are on page 1of 2

Chapter (11)

File Input/Output
File Input and Output

File handling is an important part of any web application. Python can be used to read and write
data. Also, it supports reading and writing data to files.

Operations on Files

1) Open a file: Before working with Files have to open the File. To open a File, Python
built in function open() is used. It returns an object of File which is used
with other functions. Having opened the file can be perform read, write,
etc. operations on the File.

Syntax: fileobj=open(filename , mode)

filename: It is the name of the file which you want to access.

mode: It specifies the mode in which File is to be opened. Default access


mode is read.

2) Writing to a file write() method is used to write a string into a file.

Syntax: fileobject.write(string str)

3) Reading from a file read() method is used to read data from the File.

Syntax: fileobject.read(value)

4) Closing a file Finished with the operations on File at the end need to close the file. It is
done by the close() method. close() method is used to close a File.

Syntax: fileobject.close()

Modes of File
Mode Description
r Read – Default value. Open a file for reading. Error if the file does not exist

a Append – Opens a file for appending. Creates the file if it does not exist

w Write – Opens a file for writing. Creates the file if it does not exist

x Create – Creates the specified file. Returns an error if the file exist

Python Programming Ch 11-1


KMD Computer Centre
Create the “Country.py”

openfile=open("Country.txt","w")

while 1:

country=input("Enter Country Name : ")

openfile.write(country + "\n")

finish=input("if you want to continue add data, press 'y' otherwise press 'n' :")

print ("")

if(finish!="y"):

break

openfile=open("Country.txt","r")

print ("\nThe content of the file...")

str=""

for ch in openfile:

str+=ch

print (str)

openfile.close()

Python Programming Ch 11-2

You might also like