Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
847 views
in Technique[技术] by (71.8m points)

directory - Delete string from multiple files in Python while creating a Backup

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The backup variable is trying to write to the parent of the Python working directory, not the directory you've specified at the top.

The line backup = './Backup' is overriding this. The top definition is never used.

You can erase the second definition, or use dirname(path) to determine the parent directory and work from there.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...