File Handling in Python-2
File Handling in Python-2
File handling refers to the process of performing operations on a file such as creating, opening,
reading, writing and closing it, through a programming interface. It involves managing the data
flow between the program and the file system on the storage device, ensuring that data is
handled safely and efficiently.
Hello world
GeeksforGeeks
123 456
Reading a File
Reading a file can be achieved by file.read() which reads the entire content of the file. After
reading the file we can close the file using file.close() which closes the file after reading it,
which is necessary to free up system resources.
content = file.read()
print(content)
file.close()
Output:
Hello world
GeeksforGeeks
123 456
Output:
Writing to a File
Writing to a file is done using file.write() which writes the specified string to the file. If the
file exists, its content is erased. If it doesn’t exist, a new file is created.
file.write("Hello, World!")
file.close()
It is done using file.write() which adds the specified string to the end of the file without
erasing its existing content.
Example: For this example, we will use the Python file created in the previous example.
file.close()
Closing a File
Closing a file is essential to ensure that all resources used by the file are properly released.
file.close() method closes the file and ensures that any changes made to the file are
saved
file.close()
content = file.read()
print(content)
Output:
Hello, World!
Appended text.
try:
content = file.read()
print(content)
finally:
file.close()
Output:
Hello, World!
Appended text.
• User – friendly : Python provides a user-friendly interface for file handling, making
it easy to create, read and manipulate files.
• Complexity : File handling in Python can be complex, especially when working with
more advanced file formats or operations. Careful attention must be paid to the code
to ensure that files are handled properly and securely.
• Text files: In this type of file, Each line of text is terminated with a special character
called EOL (End of Line), which is the new line character (‘\n’) in Python by default.
• Binary files: In this type of file, there is no terminator for a line, and the data is stored
after converting it into machine-understandable binary language.
File_object = open(r"File_Name","Access_Mode")
Example: Here, file1 is created as an object for MyFile1 and file2 as object for MyFile2.
• Using readline()
• Using readlines()
read(): Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the
entire file.
File_object.read([n])
readline(): Reads a line of the file and returns in form of a string.For specified n, reads at
most n bytes. However, does not reads more than one line, even if n exceeds the length of the
line.
File_object.readline([n])
readlines(): Reads all the lines and return them as each line a string element in a list.
File_object.readlines()
In this example, a file named “myfile.txt” is created and opened in write mode ( "w" ). Data
is written to the file using write and writelines methods. The file is then reopened in read
and append mode ( "r+" ). Various read operations, including read , readline ,
readlines , and the use of seek , demonstrate different ways to retrieve data from the file.
Finally, the file is closed.
file1.seek(0)
file1.seek(0)
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
Output:
• Using write()
• Using writelines()
write(): Inserts the string str1 in a single line in the text file.
File_object.write(str1)
file = open("Employees.txt", "w")
for i in range(3):
name = input("Enter the name of the employee: ")
file.write(name)
file.write("\n")
file.close()
Output:
writelines(): For a list of string elements, each string is inserted in the text file.Used to insert
multiple strings at a single time.
file1.writelines(lst)
file1.close()
print("Data is written into the file.")
Output:
# Append-adds at last
file1 = open("myfile.txt", "a") # append mode
file1.write("Today \n")
file1.close()
# Write-Overwrites
file1 = open("myfile.txt", "w") # write mode
file1.write("Tomorrow \n")
file1.close()
Output:
Access modes govern the type of operations possible in the opened file. It refers to how the
file will be used once it’s opened. These modes also define the location of the File Handle in
the file. The file handle is like a cursor, which defines from where the data has to be read or
written in the file and we can get Python output in text file.
• Read Only (‘r’): Open text file for reading. The handle is positioned at the
beginning of the file. If the file does not exist, raises the I/O error. This is also
the default mode in which a file is opened.
• Read and Write (‘r+’): Open the file for reading and writing. The handle is
positioned at the beginning of the file. Raises I/O error if the file does not
exist.
• Write Only (‘w’): Open the file for writing. For the existing files, the data is
truncated and over-written. The handle is positioned at the beginning of the
file. Creates the file if the file does not exist.
• Write and Read (‘w+’): Open the file for reading and writing. For an existing
file, data is truncated and over-written. The handle is positioned at the
beginning of the file.
• Append Only (‘a’): Open the file for writing. The file is created if it does not
exist. The handle is positioned at the end of the file. The data being written
will be inserted at the end, after the existing data.
• Append and Read (‘a+’): Open the file for reading and writing. The file is
created if it does not exist. The handle is positioned at the end of the file. The
data being written will be inserted at the end, after the existing data.
Directories in Python
In Python, directories, commonly known as folders in operating systems, are locations on the
filesystem used to store files and other directories. They serve as a way to group and manage
files hierarchically.
Python provides several modules, primarily os and os.path, along with shutil, that allows you
to perform various operations on directories.
These operations include creating new directories, navigating through existing directories,
listing directory contents, changing the current working directory, and removing directories.
This function accepts a single argument, which is a string representing a path in the
filesystem. This argument can be −
Example
In this example, we check whether the given directory path exists using the os.path.exists()
function −
import os
directory_path = "D:\\Test\\MyFolder\\"
if os.path.exists(directory_path):
print(f"The directory '{directory_path}' exists.")
else:
print(f"The directory '{directory_path}' does not exist.")
Creating a Directory
You create a new directory in Python using the os.makedirs() function. This function creates
intermediate directories if they do not exist.
The os.makedirs() function accepts a "path" you want to create as an argument. It optionally
accepts a "mode" argument that specifies the permissions o set for the newly created
directories. It is an integer, represented in octal format (e.g., 0o755). If not specified, the
default permissions are used based on your system's umask.
Example
In the following example, we are creating a new directory using the os.makedirs() function −
Open Compiler
import os
new_directory = "new_dir.txt"
try:
os.makedirs(new_directory)
print(f"Directory '{new_directory}' created successfully.")
except OSError as e:
print(f"Error: Failed to create directory '{new_directory}'. {e}")
You can use the mkdir() method of the os module to create directories in the current
directory. You need to supply an argument to this method, which contains the name of the
directory to be created.
os.mkdir("newdir")
Example
Open Compiler
import os
Syntax
os.getcwd()
Example
Following is an example to display the current working directory using the getcwd() function
−
Open Compiler
import os
current_directory = os.getcwd()
print(f"Current working directory: {current_directory}")
Example
In the example below, we are listing the contents of the specified directory path using the
listdir() function −
import os
directory_path = r"D:\MyFolder\Pictures"
try:
contents = os.listdir(directory_path)
print(f"Contents of '{directory_path}':")
for item in contents:
print(item)
except OSError as e:
print(f"Error: Failed to list contents of directory '{directory_path}'.
{e}")
Contents of 'D:\MyFolder\Pictures':
Camera Roll
desktop.ini
Saved Pictures
Screenshots
Syntax
os.chdir("newdir")
Example
Following is an example to change the current directory to Desktop using the chdir() method
−
import os
new_directory = r"D:\MyFolder\Pictures"
try:
os.chdir(new_directory)
print(f"Current working directory changed to '{new_directory}'.")
except OSError as e:
print(f"Error: Failed to change working directory to '{new_directory}'.
{e}")
Removing a Directory
You can remove an empty directory in Python using the os.rmdir() method. If the directory
contains files or other directories, you can use shutil.rmtree() method to delete it recursively.
Syntax
Example
In the following example, we remove an empty directory using the os.rmdir() method −
import os
directory_path = r"D:\MyFolder\new_dir"
try:
os.rmdir(directory_path)
print(f"Directory '{directory_path}' successfully removed.")
except OSError as e:
print(f"Error: Failed to remove directory '{directory_path}'. {e}")