File Handling in Python PDF
File Handling in Python PDF
What is a fi le ?
• f = open("test.txt")
# equivalent to 'r' or 'rt'
• f = open("test.txt",'w')
# write in text mode
•f =
open("img.bmp",'r+b')
# read and write in
binary mode
• f = open("test.txt",mode =
'r',encoding = 'utf-8')
# Specfied with encoding
Reading functions
• read(n)
– Read at most n charact ers form t he fi le. Reads
t ill end of file if it is negative or None.
• readable()
– Returns True if the file stream can be read
from.
• readline(n=-1)
– Read and ret urn one line from t he fi le.
Reads in at most n bytes if specified.
• readlines(n=-1)
– Read and return a list of lines from the file.
Reads in at most n bytes/characters if
specified.
read( )
readline( )
readlines( )
Example:
with open("test.txt",'w') as f:
f.write("my first file\n")
f.write("This file\n\n")
f.write("contains three lines\n")
File writing methods
• writable()
– Returns True if the file stream can be
written to.
• write(s)
– Write string s to the file and
return the number of characters
written.
• writelines(lines)
– Write a list of lines t o t he fi le.
Sample File copy operation