0% found this document useful (0 votes)
5 views22 pages

Iv - File Handling

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 22

PYTHON

FILE HANDLING
ITE103 – PROGRAMMING 2
What is file handling in Python?
◦Python File Handling is the process of creating,
reading, writing, updating, and deleting files in a
computer's file system.
◦File handling in Python is used to store data
permanently in a file or to read data from an existing
file.
C R U D
CREATE READ UPDATE DELETE

Four basic functions that are commonly used


when working with databases and user interfaces
File handling is an important
concept in Python programming

◦ It allows you to work with files in a computer's


file system
Importance of using file handling in
Python
◦Data Storage
◦Data Analysis
◦Automation
◦Data Transfer
◦Integration with other technologies
Creating a new text file
file = open(”spup.txt", "w")
file.write("This is a new text file!")
file.close()
Try this:
◦Create a Python program that prompts the user
to input a file name and creates a new text file
with that name
Solution
filename = input("Enter a file name: ")
file = open(filename, "w")
file.close()
print("File", filename, "created
successfully!")
Create a textfile: iamspup.txt
VISION
St. Paul University Philippines is an internationally recognized institution dedicated to
the formation of competent leaders and responsible citizens of their communities,
country, and the world.

MISSION
Animated by the Gospel and guided by the teachings of the Church, it helps to uplift the
quality of life and to effect social transformation through:
1.Quality, Catholic, Paulinian formation, academic excellence, research, and community
services;
2.Optimum access to Paulinian education and service in an atmosphere of
compassionate caring; and,
3.Responsive and innovative management processes.
Opening a text file
file = open("iamspup.txt", "r")
content = file.read()
print(content)
file.close()
Let’s do it together!
import os

folder_path = "path/to/folder" # replace with the actual


folder path
for filename in os.listdir(folder_path):
if filename.endswith(".txt"):
print(filename)
Let’s Improve the Code
import os

folder_path = "path/to/folder" # replace with the actual folder path


for filename in os.listdir(folder_path):
if filename.endswith(".txt"):
file_path = os.path.join(folder_path, filename)
with open(file_path, "r") as file:
content = file.read()
print("Contents of", filename, "file:")
print(content)
Try this:
◦Create a Python program that prints all .txt files
in a folder, prompts the user to select a file, and
displays its contents:
import os
folder_path = "path/to/folder" # replace with the actual
Solution folder path
txt_files = [ ] # create an empty list to store the .txt files
# loop through all files in the folder and add .txt files to
the list
for filename in os.listdir(folder_path):
if filename.endswith(".txt"):
txt_files.append(filename)
# print the list of .txt files
print("Available text files in the folder:")
for i, filename in enumerate(txt_files):
print(i+1, filename)
# prompt the user to select a file
Solution selection = int(input("Enter the number of the text
(Continuation) file you want to read: "))
selected_file = txt_files[selection-1]
file_path = os.path.join(folder_path, selected_file)

# open the selected file and display its contents


with open(file_path, "r") as file:
content = file.read()
print("\nContents of", selected_file, "file:\n")
print(content)
Updating a text file
file = open(”iamspup.txt", "w")
file.write(”Making a Difference Globally!")
file.close()
Delete a text file
import os
file_path = "path/to/file.txt" # replace with the actual file
path

if os.path.exists(file_path):
os.remove(file_path)
print(f"{file_path} has been deleted.")
else:
print(f"{file_path} does not exist.")
Try this:
◦Create a Python program that prints all .txt files
in a directory, prompts the user to select a file
for deletion, and then deletes the selected file:
import os

Solution folder_path = "path/to/folder" # replace with the


actual folder path
txt_files = [ ] # create an empty list to store the .txt
files
# loop through all files in the folder and add .txt files
to the list
for filename in os.listdir(folder_path):
if filename.endswith(".txt"):
txt_files.append(filename)

# print list of txt files


print("List of .txt files in folder:")
for file in txt_files:
print(file)
# prompt user to select a file for deletion
Solution file_to_delete = input("Enter the name of the
(Continuation) file to delete (including .txt extension): ")

# check if selected file exists and delete if it


does
if file_to_delete in txt_files:
os.remove(os.path.join(folder_path,
file_to_delete))
print(f"{file_to_delete} has been deleted.")
else:
print(f"{file_to_delete} does not exist in the
folder.")
Hands-on Quiz:
◦Create a Python program that accepts a
student’s first name, middle name and last
name and writes the processed data to a new
file using the format:
inputtedstudentlastname_programming2.txt
first_name = input("Enter your first name: ")
middle_name = input("Enter your middle name: ")
Solution last_name = input("Enter your last name: ")

# Concatenate the last name and file extension to


create the file name
file_name = last_name.lower() +
"_programming2.txt"

# Open the file in write mode


with open(file_name, "w") as file:
# Write the student's name to the file
file.write(f"First Name: {first_name}\n")
file.write(f"Middle Name: {middle_name}\n")
file.write(f"Last Name: {last_name}\n")

print(f"Data written to {file_name}.")

You might also like