Modify files by removing or editing lines
Typical workflow: read the file, process the lines in memory, and write the result back (either to the same file or a new one). Use a with block to ensure files close cleanly.
Splitting lines from a file
Use .split(",") to break comma-separated values into fields.
# Example: Splitting a CSV line
line = "Inception,Leonardo DiCaprio,Sci-Fi,2010,9.0"
fields = line.split(",")
print("Movie:", fields[0])
print("Year:", fields[3])
Practice Task 1: Movies file
Task 1: Create and print movie names
Create movies.txt with lines: movie, actor, genre, year, rating. Print just the movie name and release year.
Show sample solution
# Read and display movie name and release year
with open("movies.txt", "r") as file:
for line in file:
# Format: movie, actor, genre, year, rating
parts = line.strip().split(",")
print("Movie:", parts[0], "- Released in", parts[3])
Deleting lines by exact match
Read all lines, filter out the exact text to remove (careful with trailing whitespace), then overwrite the file.
# Remove a specific line from a file
with open("data.txt", "r") as file:
lines = file.readlines()
line_to_remove = input("Enter the exact line to delete: ").rstrip()
with open("data.txt", "w") as file:
for line in lines:
if line.rstrip() != line_to_remove:
file.write(line)
print("The specified line has been removed.")
Deleting lines containing a specific word
For partial/contains matching, compare lowercase strings.
# Remove lines containing a specific word
with open("data.txt", "r") as file:
lines = file.readlines()
keyword = input("Enter the keyword to remove lines: ").lower()
with open("data.txt", "w") as file:
for line in lines:
if keyword not in line.lower():
file.write(line)
print("Lines containing the keyword have been removed.")
Practice Task 2: Tree file modification
Task 2: Remove trees from a file
Using trees.txt, let the user choose: remove a specific tree (exact match) or remove any line that contains a given type (partial match).
Show sample solution
# Read file contents
with open("trees.txt", "r") as file:
tree_lines = file.readlines()
choice = input("Type 'specific' to remove a specific tree or 'type' to remove by tree type: ").lower()
if choice == "specific":
tree_to_remove = input("Enter the exact tree name to remove: ").strip()
new_lines = [line for line in tree_lines if line.strip() != tree_to_remove]
elif choice == "type":
tree_type = input("Enter the tree type to remove: ").lower().strip()
new_lines = [line for line in tree_lines if tree_type not in line.lower()]
else:
new_lines = tree_lines
with open("trees.txt", "w") as file:
for line in new_lines:
file.write(line)
print("File updated successfully.")
Sorting a file
Load the lines, sort them (optionally reverse), then write back.
# Read and sort the file contents
with open("trees.txt", "r") as file:
tree_list = file.readlines()
tree_list.sort() # For reverse order use: tree_list.sort(reverse=True)
with open("trees.txt", "w") as file:
for line in tree_list:
file.write(line)
print("The file has been sorted.")
Practice Task 3: Enhanced tree file
Task 3: Sort or remove trees
Let the user type sort (asc/desc) or remove (delete any lines containing a term).
Show sample solution
with open("trees.txt", "r") as file:
trees = file.readlines()
action = input("Enter 'sort' to sort or 'remove' to delete lines: ").lower()
if action == "sort":
order = input("Type 'asc' for ascending or 'desc' for descending order: ").lower()
trees.sort(reverse=(order == "desc"))
elif action == "remove":
term = input("Enter the tree name or type to remove: ").lower()
trees = [line for line in trees if term not in line.lower()]
with open("trees.txt", "w") as file:
file.writelines(trees)
print("The trees file has been updated.")
Editing specific lines in a file
When updating records, write to a new file (or a temp file) and then replace the original. This avoids corrupting data if something goes wrong mid-write.
# Example: Update the rating in a movie record
with open("movies.txt", "r") as file:
lines = file.readlines()
movie_to_update = input("Enter the movie name to update its rating: ").strip()
new_rating = input("Enter the new rating: ")
with open("movies_temp.txt", "w") as temp_file:
for line in lines:
if movie_to_update.lower() in line.lower():
parts = [p.strip() for p in line.strip().split(",")]
# Format: title, actor, genre, year, rating
parts[-1] = new_rating
temp_file.write(", ".join(parts) + "\n")
else:
temp_file.write(line)
print("The movie rating has been updated in movies_temp.txt")
Practice Task 4: Update movie rating
Task 4: Edit the movie file
Ask for a movie title and a new rating (out of 10). Update the rating and save to a new file.
Show sample solution
# Read all movie records
with open("movies.txt", "r") as file:
movie_lines = file.readlines()
movie_title = input("Enter the movie title to update: ").strip()
new_rating = input("Enter the new rating: ")
with open("movies_updated.txt", "w") as file:
for line in movie_lines:
# Format: title, actor, genre, year, rating
details = [p.strip() for p in line.strip().split(",")]
if details and movie_title.lower() == details[0].lower():
details[-1] = new_rating
file.write(", ".join(details) + "\n")
else:
file.write(line)
print("The movie file has been updated in movies_updated.txt")
Tips & good practice
- Use
with open(...)so files always close properly. - Trim lines with
.strip()/.rstrip()when comparing. - Consider writing to a temp file and swapping it in after success.
- When dealing with CSV, a missing comma can break splitting—validate inputs.