Py 05
Py 05
5
Exploring Files and directories: Python program to append
data to existing file and then display the entire file
Date of Performance:7/2/25
Date of Submission:14/2/25
Experiment No. 5
Title: Exploring Files and directories: Python program to append data to existing file and then
display the entire file
Aim: To Exploring Files and directories: Python program to append data to existing file and then
display the entire file
Theory:
Directory also sometimes known as a folder are unit organizational structure in computer’s file
system for storing and locating files or more folders. Python now supports a number of APIs to
list the directory contents. For instance, we can use the Path.iterdir, os.scandir, os.walk,
Path.rglob, or os.listdir functions.
Python too 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. The concept of file handling has
stretched over various other languages, but the implementation is either complicated or lengthy,
but alike other concepts of Python, this concept here is also easy and short. Python treats file
differently as text or binary and this is important. Each line of code includes a sequence of
characters and they form text file. Each line of a file is terminated with a special character, called
the EOL or End of Line characters like comma {,} or newline character. It ends the current line
and tells the interpreter a new one has begun. Let’s start with Reading and Writing files.
We use open () function in Python to open a file in read or write mode. As explained above, open
( ) will return a file object. To return a file object we use open() function along with two
arguments, that accepts file name and the mode, whether to read or write. So, the syntax being:
open(filename, mode). There are three kinds of mode, that Python provides and how files can be
opened:
“ r “, for reading.
“ w “, for writing.
“ a “, for appending.
CODE:
try:
file.write(data + "\n")
except Exception as e:
def read_file(filename):
try:
content = file.read().strip()
if content:
print("\nFile Content:\n")
print(content)
else:
except FileNotFoundError:
except Exception as e:
if __name__ == "__main__":
new_data = input("Enter the text you want to append to the file: ")
append_to_file(file_name, new_data)
read_file(file_name)
OUTPUT:
Conclusion:
Python provides efficient and easy-to-use file handling capabilities with built-in functions like
open(), read(), write(), and append(). It supports various file modes, automatic
resource management using with statements, and error handling for robust file operations. Its
simplicity and cross-platform compatibility make it ideal for handling large-scale file processing
tasks efficiently.