14 - File Input Output
14 - File Input Output
Learning objective
• File Handling
• Opening and Closing Files
• The open Function
• The file Object Attributes
• The close() Method
• Reading and Writing Files
• The write() and write() Methods
• More operations on files
File Handling - Introduction
• Manipulation of files, which involves reading from and writing to
files.
• Python supports file handling and allows users to handle files i.e.,
to read and write files, along with many other file handling options,
to operate on files.
Opening and Closing Files
• Until now, you have been reading and writing to the standard input
and output. Now, we will see how to use actual data files.
• When working with files, you need to specify the mode in which
you want to open the file.
The open() Function
• Before you can read or write a file, you have to open it using Python's
built-in open() function.
• This function creates a file object, which would be utilized to call
other support methods associated with it.
• We use open() function in Python to open a file in read or write mode.
“ r “, for reading.
“ w “, for writing.
“ a “, for appending.
“ r+ “, for both reading and writing
“ab” for appending in binary format
“rb“ for reading only in binary format
“rb+“ for both reading and writing in binary format
“wb “ for writing only in binary format
“w+” for both reading and writing
“wb+“for both reading and writing in binary format
• One must keep in mind that the mode argument is not mandatory.
• If not passed, then Python will assume it to be “ r ” by default.
• "w" (Write): Opens the file for writing. If the file already exists, its
contents are truncated. If the file doesn't exist, a new file is
created.
file1 = open(“Hello.txt", "w")
The file Object Attributes
• Once a file is opened and you have one file object, you can get
various information related to that file.
• The file object attributes are:
• Syntax :
• fileObject.close();
Reading and Writing files
• The file object provides a set of access methods to make our lives
easier.
• We will see how to use read() and write() methods to read and
write files.
Example: Opens the file for writing, but appends new data to the
end of the file instead of truncating it.
file = open("Hello.txt", "a")
file.write("I am fine. Thank you!" + "\n")
file.close()
Using with statement
• A better practice is to use the with statement, known as a context
manager.
• It automatically closes the file when the code block is exited.
• It will create the file, if it doesn’t exist. Then writes to the file and finally
reads the content from the file.
• To use this module you need to import it first and then you can call any
related functions.
rename() Method
• The rename() method takes two arguments, the current filename
and the new filename.
• Syntax
os.rename(current_file_name, new_file_name)
import os
os.rename( " Good1.txt ", " Good2.txt " )
remove() method
• You can use the remove() method to delete files by supplying the
name of the file to be deleted as the argument.
• Syntax :
os.remove(file_name)
import os
os.remove(“Good2.txt")
Write code to delete the file, if the file doesn’t
exist, display file doesn’t exist.
import os
filename="hello.txt"
if os.path.exists(filename):
os.remove(filename) # Remove the file
print(f"{filename} has been removed.")
else:
print(f"{filename} does not exist.")
Program to combine data from files
with open("1880-boys.txt") as f_boys:
boys = f_boys.read()
os.mkdir("my_files/a")
os.makedirs("my_files/a/b/c")
foo = 'my_files/foo.txt'
bar = 'my_new_files/bar.txt'
def foo2bar():
os.renames(foo, bar)
print('Renamed', foo, 'to', bar)
def bar2foo():
os.renames(bar, foo)
print('Renamed', bar, 'to', foo)
foo2bar()
Enumerate()
• enumerate(iterable, start=0)
• Split() method has the same functionality but works with less
newline characters
enumerate(iterable, start=0)
def main():
with open('my_files/states.txt') as f:
states = f.read().splitlines()
main()
Using len() function
def main():
with open('my_files/states.txt') as f:
states = f.read().splitlines()
main()
Using splitlines()
with open('my_files/zen_of_python.txt') as f:
poem = f.read()