0% found this document useful (0 votes)
10 views29 pages

14 - File Input Output

The document provides an overview of file handling in Python, covering topics such as opening and closing files, the open() function, file object attributes, and methods for reading and writing files. It also discusses best practices like using the with statement for file operations, as well as file manipulation techniques such as renaming and deleting files using the os module. Additionally, it includes examples of combining data from files, listing directory contents, and using functions like enumerate() and splitlines().

Uploaded by

Arif Ahmad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views29 pages

14 - File Input Output

The document provides an overview of file handling in Python, covering topics such as opening and closing files, the open() function, file object attributes, and methods for reading and writing files. It also discusses best practices like using the with statement for file operations, as well as file manipulation techniques such as renaming and deleting files using the os module. Additionally, it includes examples of combining data from files, listing directory contents, and using functions like enumerate() and splitlines().

Uploaded by

Arif Ahmad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

File handling in Python

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.

• There are built-in functions and methods for performing various


file-related operations.

• 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.

• Python provides basic functions and methods necessary to


manipulate files by default. You can do your most of the file
manipulation using a file object.

• 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.

File_object = open(file_name [, access_mode][,buffering])


The open() Function access modes
• The access_mode determines the mode in which the file has to be
opened, i.e., read, write, append, etc.

“ 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.

• Buffering(Optional): If the buffering value is set to 0, no buffering


takes place. If the buffering value is 1, line buffering is performed
while accessing a file.
• If you specify the buffering value as an integer greater than 1, then
buffering action is performed with the indicated buffer size. If
negative, the buffer size is the system default (default behavior).
The open() Function
• "r" (Read): Opens the file for reading. Raises an error if the file
does not exist.
file = open(“Hello.txt", "r")

• "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:

• file.closed : Returns true if file is closed, false otherwise.


• file.mode : Returns access mode with which file was opened.
• file.name : Returns name of the file.
• file.softspace : Returns false if space explicitly required with print,
true otherwise.
The close() method
• The close() method of a file object flushes any unwritten
information and closes the file object, after which no more writing
can be done.
• Python automatically closes a file when the reference object of a
file is reassigned to another file.
• It is a good practice to use the close() method to close a file.

• 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.

• read(): Reads the entire content of the file.

• write(data): Writes the specified data to the file.


Reading data from files
file = open("Hi.txt", "r")
content = file.read()
print(content)

f = open("hi.txt") # Open hi.txt and assign result to f.


content = f.read() # Read contents of file into content variable.
print(content) # Print content variable data
f.close() # Close the file.
Writing data to files
#writing data to the file
F = open("Hello.txt", 'w')
F.write("Hello, Good Morning")
F.close()

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.

with open("example.txt", "w") as file:


file.write("Hello, World!\n")
file.write("This is a sample file.")
with open("example.txt", "r") as file:
content = file.read()
print(content)
Renaming and Deleting files
• Python os module provides methods that help you perform file-
processing operations, such as renaming and deleting files.

• 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()

with open("1880-girls.txt") as f_girls:


girls = f_girls.read()

with open("1880-all.txt", "w") as f:


f.write(boys + "\n" + girls)
List directory contents
import os
dir_contents = os.listdir("my_files")
for item in dir_contents:
print(item)
Make copy of a file
f1 = open('my_files/logo.png', 'rb')
f2 = open('my_files/logo2.png', 'wb')
f2.write(f1.read())
f1.close()
f2.close()
Create directories, sub directories and files
import os

os.mkdir("my_files/a")
os.makedirs("my_files/a/b/c")

with open('my_files/a/a-demo.txt', 'w') as f:


f.write('Dummy text')
with open('my_files/a/b/b-demo.txt', 'w') as f:
f.write('Dummy text')
Renaming files
import os

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)

• iterable: The sequence (list, tuple, string) you want to enumerate


over.
• start (optional): The starting index for enumeration (default is 0).

• Enumrate() function loops through an iterable while keeping track


of the index of each item.
• Accesses both the index and the value of items in an iterable.
Splitlines()
• Splitlines() method is used to split a string into a list of lines,
based on the line boundaries (e.g., newline characters \n, \r, or
\r\n).
• It is particularly helpful for processing multiline strings.

• 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()

for i, state in enumerate(states, 1):


state_name = state.split('\t')[0]
print(f'{i}. {state_name}')

main()
Using len() function
def main():
with open('my_files/states.txt') as f:
states = f.read().splitlines()

print(f'The file contains {len(states)} states.')

main()
Using splitlines()
with open('my_files/zen_of_python.txt') as f:
poem = f.read()

for i, line in enumerate(poem.splitlines(), 1):


print(f"{i}. {line}")
You must have learnt:
• 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

You might also like