Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
965 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...