2
3 Lesson objectives
3 File handling
3 Appending data
3 Writing data
3 Source Code
PYTHON PROGRAMMING
3
By the end of this lesson, you should be able to:
Understand the importance of file handling
Learn how to append data to an existing file and writing data to a file
File handling in Python refers to the ability to work with files, which are external resources used to store data
persistently. Python provides built-in functions and modules that allow programmers to perform various operations
on files, such as creating, reading, writing, and deleting files.
Appending data in Python using file handling involves adding new data to the end of an existing file without
overwriting the existing content. This can be achieved using the ‘a’ mode in Python's file handling operations. It's
important to note that in append mode, new data is always added to the end of the file, even if the file is opened
multiple times. Existing data in the file remains unchanged, and the new data is simply added to the end.
To write data to a file in Python, you can open a file using the open() function with a specified file name, mode (such
as 'w' for write), and optionally encoding, and then use the write() method to write data to the file. You can write
data to a file in Python using different methods, such as writing a single string or a list of strings, numbers, or other
data types. You can also write data in binary or text mode, depending on the type of data you want to store. After
writing data to a file, it is important to close the file using the close() method to ensure that the data is properly
saved and the file is released from memory.
# Append text to a new line
with open('file_1.txt', 'a') as file:
[Link]("\nThis is some new text which was appended")
#Write data and overwrite existing data
with open('file_1.txt', 'w') as file:
[Link]("This text overwrites all existing data in text file")
# Create a new file
with open('file_2.txt', 'w') as file:
[Link]("This is a new file which was created using Python")
[Link]()
PYTHON PROGRAMMING
4
#Print a list of fruits
fruit_list = ['Apple ', 'Orange ', 'Bananas ', 'Grapes', 'Peach']
with open('[Link]', "w") as list_of_fruits:
for fruit in fruit_list:
list_of_fruits.write("\n"+ fruit)
content = open('[Link]')
print([Link]())
#print amount of words in a text file
def count_words(file_path):
with open(file_path) as file:
data = [Link]()
[Link](",", " ")
return len([Link](" "))
print(count_words("metcalfes_law.txt"))
employee\'s ID is {row["employee_id"]}.')
line_count+=1
PYTHON PROGRAMMING