Python: How to replace dashes in filenames?
The question is related to the answer about renaming files recursively.
The code, changed to replace dashes, does not work with cases such as:
./Beginners Tools/Hello's -Trojans-/bif43243
./Linux/Nux Col - 1 Works (TEX & Pdf) - T'eouhsoe & More (33323 - 34432)
./Git/peepcode-git-mov/c6_branch_merge.mov
./haskell/OS 2007 - T aoue
./B Sites for Get-Big
It worked with cases such as:
./oeu'oeu - X ee ls - Feb 2008.pdf
So I need to parse the data. How can I correctly repl开发者_开发技巧ace dashes?
[Details]
The code is from the link, but changed to replace "-":
import os
for dirpath, dirs, files in os.walk(your_path):
for filename in files:
if '&' in filename:
os.rename(
os.path.join(dirpath, filename),
os.path.join(dirpath, filename.replace('-', '_'))
)
The Python did not replace every dash. I think it is because the names contains special signs that stopped the script earlier. So I encountered errors in archieving:
tar cvzf sed_backup.tar.gz `find documents | sed s/\.*/\'\&\'/`
tar: rojans-: Cannot stat: No such file or directory
tar: Error is not recoverable: exiting now
Because of the signs " ' " and " - " still left in the names, the tar-command interpret " ' " as an end for the find-command and " - " as an option sign in the path "./Beginners Tools/Hello's -Trojans-/bif43243"
The os.path.walk is handy for traversing file system trees, a simple example:
import os, shutil
def rename_file(arg, dirname, filename):
filepath = os.path.join(dirname, filename)
# check if file meets your rename condition here
if os.path.isfile(filepath):
new_name = "something"
shutil.move(filepath, os.path.join(dirname, new_name)
os.path.walk(base_dir, rename_file, None)
Regards Arthur
Most likely your problem is the single quotes, the parenthesis and the dashes. You can either escape them or replace them.
Actually looking at your edit, the original code you linked to is replacing characters in the filename not the whole path. You need to escape the characters in the path:
esc_dirpath = dirpath.replace('-','\-')
That's fairly simplistic, one could also use a regex to escape a set of characters.
I would recommend running that os walk and print out the special cases before and after the escaping/replacing of those characters before you actually do the rename.
this post might help: python script to recursively replace string in filename and contents
精彩评论