Professional Documents
Culture Documents
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.
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
openfile=open("Country.txt","w")
while 1:
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")
str=""
for ch in openfile:
str+=ch
print (str)
openfile.close()