递归删除文件夹/文件名中的字符
我开始写一个脚本,用来从Linux系统中删除非法字符。先处理文件,然后处理文件夹。到目前为止,我的进展是这样的 -
import sys
import os
import re
# List of illegal chars to run through to replace in the filesystem walk
chars = ['~', '*', '\\', ':', '<', '>', '|', '?', '"']
def ReplaceChars(value):
for c in chars:
value = value.replace(c, '')
return value
def RenamePath(path):
newFilePath = ReplaceChars(path)
os.rename(path, newFilePath)
def WalkFileSystem(dirroot):
# Main Walk Through File System
for root, dirs, files in os.walk(dirroot, topdown=False):
for name in files:
searchObj = re.search(r'[%s]' % ''.join(chars), os.path.join(root, name))
if searchObj:
RenamePath(os.path.join(root, name))
for name in dirs:
searchObj = re.search(r'[%s]' % ''.join(chars), os.path.join(root, name))
if searchObj:
RenamePath(os.path.join(root, name))
if __name__ == "__main__":
# Calls the WalkFileSystem Function
WalkFileSystem('/TestFolder/')
在某些情况下,这个脚本是有效的。不过问题是,如果我有一个目录名像是 *test/,那么os.rename就不太喜欢这个名字,因为它在尝试重命名这个目录下的文件时,没有处理好路径中的这个通配符(我猜这就是问题所在)。
我有两个问题 -
- 我该如何解决这个问题呢?
- 这样做算不算是最符合Python风格的做法,还是我走偏了?
更新带有工作示例
import argparse
import os
import re
# List of illegal chars to run through to replace in the filesystem walk
chars = ['~', '*', '\\', ':', '<', '>', '|', '?', '"']
def ReplaceChars(value):
for c in chars:
value = value.replace(c, '')
return value
def RenamePath(root, path):
newFilePath = ReplaceChars(path)
os.rename(os.path.join(root, path), os.path.join(root, newFilePath))
def WalkFileSystem(dirroot):
# Main Walk Through File System
for root, dirs, files in os.walk(dirroot, topdown=False):
for name in dirs:
searchObj = re.search(r'[%s]' % ''.join(chars), name)
if searchObj:
RenamePath(root, name)
for name in files:
searchObj = re.search(r'[%s]' % ''.join(chars), name)
if searchObj:
RenamePath(root, name)
if __name__ == "__main__":
# Calls the WalkFileSystem Function
WalkFileSystem('/home/mpashby/Scripts/TestFolder/')
谢谢,
1 个回答
0
这是因为,当你的脚本运行 RenamePath 的时候,它大概是这样做的:
>>> os.rename(str('/testdir/*test/h.txt'), '/testdir/test/h.txt')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory
你试图用一个还不存在的目录来重命名路径(/testdir/test/h.txt),所以你会遇到错误。
下面这个就能正常工作。
>>> os.rename(str('/testdir/*test/h.txt'), '/testdir/*test/g.txt')
>>>
不过,你不想要任何特殊字符,所以我建议你先把目录路径中的特殊字符去掉,再去处理文件,这样就不会出现“没有这样的文件或目录”的错误了。