I need to remove the string 'HELLO' from multiple .txt files in Python. Before doing so, I want to copy all those files to a backup folder.
I have my files in the drc folder and I created a backup folder, but my code is not saving the copies to the Backup folder, instead it's saving them to the main Project folder.
drc = 'C:/Users/Bear/Desktop/Project/Files'
backup = 'C:/Users/Bear/Desktop/Project/Backup'
pattern = re.compile('HELLO')
oldstr = 'HELLO'
newstr = ''
for dirpath, dirname, filename in os.walk(drc):
for fname in filename:
path = os.path.join(dirpath, fname)
backup = './Backup'
strg = open(path).read()
if re.search(pattern, strg):
shutil.copy2(backup, fname)
strg = strg.replace(oldstr, newstr)
f = open(path, 'w')
f.write(strg)
f.close()
Sometimes I get PermissionError: [Errno13] Permission denied: './Backup'.
I think my problem is specifying the paths, also I would like my paths to be relative, not absolute, so that someone else can replicate this project.
question from:
https://stackoverflow.com/questions/65868728/delete-string-from-multiple-files-in-python-while-creating-a-backup 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…