File tree Expand file tree Collapse file tree 1 file changed +12
-7
lines changed Expand file tree Collapse file tree 1 file changed +12
-7
lines changed Original file line number Diff line number Diff line change 1
- # TODO: make sure that program does not overwrite file contents
2
1
import os
3
2
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 ()
10
7
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 )} " )
11
16
12
17
occurance_remover (r"C:\Users\s158658\src\python-programming\lab-12\test.txt" , "foo" )
You can’t perform that action at this time.
0 commit comments