2. Files
• Opening a file
• Python has a built-in open() function, which
takes a filename as an argument.
• Filename argument can just denote a file• Filename argument can just denote a file
name or the path of the file.
• The path can be absolute or relative.
• In python, / is used to specify the path
• Ex: afile = open(‘test.txt’)
3. Absolute vs Relative Path
• Absolute Path:
– Always starts from the root path, in windows from the
drive letter.
• Relative Path:• Relative Path:
– It’s the path with respect to the current dirctory.
TASK:
Try to specify the file path in windows style (using )
4. Stream Objects
• The open() function returns a stream object,
which has methods and attributes for getting
information about and manipulating a stream
of characters.of characters.
afile = open(‘test.txt’)
print afile.name
print afile.mode
• mode is ‘r’ by default
5. Files
• Reading a file
• File is read by calling a read() method of the stream
object
• The result is a string
• TASK
df = open(‘test.txt')
print df.read()
print "Read Again"
print df.read()
6. Files - Reading
• Reading a file twice don’t give any exception but
simply returns a empty string.
• So how to re-read a file? Let’s see:
– afile.read()
afile.seek(0)
afile.read()afile.read()
• seek() method moves the control to a specific byte position
• read() method takes optional parameters to read the specific
number of characters
• tell() method of the stream object is used to know thw
current position of the pointer(in simple words, the
cursor)
7. Files Reading
• seek(offset[, from])
• The offset argument indicates the number of bytes to be moved.
• The from argument specifies the reference position from where the bytes
are to be moved.
– If from is set to 0, it means use the beginning of the file as the reference– If from is set to 0, it means use the beginning of the file as the reference
position and 1 means use the current position as the reference position and if
it is set to 2 then the end of the file would be taken as the reference position.
8. Files
• Note:
• The seek() and tell() methods always count bytes, but since you
opened this file as text, the read() method counts characters
• (In case of English characters, both are same)
• TASK
df = open(‘test.txt')
print df.read()
Now try to move the file to some other folder. Lets see what happens
9. Files - Close
• Closing a File
• Open file consume some resources, depending on the file
mode, Its important to close the file once its used.
• afile.close()
• Attribute closed will return if a file is closed or not.• Attribute closed will return if a file is closed or not.
• afile.closed return true or false.
• close() just closes a file but not destroy the afile object.
10. File - Close
• You can’t read from a closed file; that raises an IOError
exception.
• You can’t seek in a closed file either.
• There’s no current position in a closed file, so the tell()
method also fails.method also fails.
• Perhaps surprisingly, calling the close() method on a
stream object whose file has been closed does not
• raise an exception. It’s just a no-op.
• Closed stream objects do have one useful attribute: the
closed attribute will confirm that the file is closed.
11. File – Automatic Close
• To make sure the file is closed even if the program is crashed by using
try(), finally block.
• (Lets see what is it in later stages)
• But python 2.6 has a better solution:
with open('examples/chinese.txt', encoding='utf-8') as a_file:
a_file.seek(17)
a_character = a_file.read(1)a_character = a_file.read(1)
print(a_character)
• This code calls open(), but it never calls a file.close(). The with
statement starts a code block, like an if statement or a for loop.
• Inside this code block, you can use the variable a file as the stream
object returned from the call to open(). All the regular stream object
methods are available — seek(), read() etc
• When the with block ends, Python calls a_file.close() automatically.
12. Reading a Line at a time
• for a_line in a_file:
• Reads one line from a_file
• TASK – GENERAL
Write a program to generate first 10 numbers of the fibonacci• Write a program to generate first 10 numbers of the fibonacci
series
• Ex: 0,1,1,2,3,5 …..
13. File - Writing
• For writing to a file, open the file in write mode.
• There are 2 modes for writing:
– Write mode - mode = ‘w’ as parameter in open()
• Overwrite the data from the beginning of the file (Previous content is lost)
– Append mode - mode = ‘a’ as parameter in open()
• Adds data to the end of the file
Both creates a file automatically if it doesn’t existBoth creates a file automatically if it doesn’t exist
Ex: 1. df = open(‘test.txt’, mode = ‘w’)
df.write(‘python’)
df.close()
2. df = open(‘test.txt’, mode = ‘w’)
df.write(‘python’)
df.close()
By default, the mode is ‘r’ (read) hence its not specific while reading.
14. Binary Files
• Few files has to be opened in binary mode.
• Ex: Image Files
• an_image = open('examples/beauregard.jpg', mode='rb’)
• We just need to mention the mode as b along with w or r to• We just need to mention the mode as b along with w or r to
specify it’s a binary file.
15. Renaming Files
• Python os module provides methods that help
you perform file-processing operations, such
as renaming and deleting files.
• The rename() Method:• The rename() Method:
• os.rename(current_file_name, new_file_name)
• Ex:
import os
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )
16. Deleting Files
• The remove() Method:
• os.remove(file_name)
• Syntax:
import osimport os
# Delete file test2.txt
os.remove("text2.txt")
17. Python Directories
• Python can handle directory option using the
os module
• mkdir()
• Creates directories in the current directory.• Creates directories in the current directory.
• Syntax:
• os.mkdir("newdir")
18. Python directories
• The getcwd() Method:
• getcwd()
• The getcwd() method displays the current working
directory.
• os.getcwd()
• The rmdir() Method:
• os.rmdir('dirname')
• The rmdir() method deletes the directory, which is passed
as an argument in the method.
• Before removing a directory, all the contents in it should be
removed.
19. TASK - GENERAL
• Write a program to check if a given string is
palidrome
• Ex: MADAM is a palindrome
20. References
• Dive into Python
• http://www.tutorialspoint.com/python/pytho
n_files_io.htm