Skip to content

Commit b28445f

Browse files
committed
fixed occurances not removing
1 parent 6dda33c commit b28445f

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

lab-12/occurance-remover.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
1-
# TODO: make sure that program does not overwrite file contents
21
import os
32
def occurance_remover(file_path, removal_string):
4-
target_file = open(file_path, "r+")
5-
occurances = target_file.read().count(removal_string)
6-
if removal_string in target_file.read():
7-
removal_string = removal_string.replace(removal_string, "")
8-
target_file.close()
9-
print(f"Removed {occurances} of {removal_string} from {os.path.basename(file_path)}")
3+
occurances = open(file_path, "r").read().count(removal_string)
4+
# Read in the file
5+
with open(file_path, "r") as file:
6+
filedata = file.read()
107

8+
# Remove the string given from the file
9+
filedata = filedata.replace(removal_string, "")
10+
11+
# Write the contents to the file without the removal strings
12+
with open(file_path, 'w') as file:
13+
file.write(filedata)
14+
file.close()
15+
print(f"Removed {occurances} occurances of {removal_string} from {os.path.basename(file_path)}")
1116

1217
occurance_remover(r"C:\Users\s158658\src\python-programming\lab-12\test.txt", "foo")

0 commit comments

Comments
 (0)