我一直在处理一个问题,我需要将大量的Mac文件和文件夹存档,并需要将它们存档在Windows服务器数据磁带上。
当我到达.DS_store文件和其他mac字符时,会出现问题和挂断。所以我需要在移动到windows之前基本上做一个清理步骤。
还有一件事就是寻找像子弹字符这样的非拉丁字符,然后删除它们或用_(下划线字符)替换它们。我无法让它工作。
跑步时抱怨压痕,而我的任何操纵都没有结果。处理非拉丁字符的代码区域是否正常?
任何帮助将不胜感激。
#!/bin/python
import os
import sys
# Help function
def showhelp():
print "Usage: delete-dsstore.py PATH"
print "Example: delete-dsstore.py /Users/angelito"
if len(sys.argv) > 1:
# Check if parameter is a dir
if os.path.isdir(sys.argv[1]):
# Clear file counter
i = 0;
# Get path
path = sys.argv[1];
# Runs through all files in the directory
for root, sub, files in os.walk(path):
for file in files:
# Checks if exists .DS_Store file
if file == ".DS_Store":
# Get full path of current .DS_Store file
fullpath = os.path.abspath(os.path.join(root, file))
print "Deleting " + fullpath
# Remove file
os.remove(fullpath)
i += 1
# Checks if exists .localized file
if file == ".localized":
# Get full path of current .localized file
fullpath = os.path.abspath(os.path.join(root, file))
print "Deleting " + fullpath
# Remove file
os.remove(fullpath)
i += 1
# Runs through all files in the directory
for root, sub, files in os.walk(path):
# Checks if exists non latin characters like bullets in file names, and delete characters
for file in files:
os.rename(file, file.encode('latin-1', 'ignore'))
# Get full path of current non latin character file
fullpath = os.path.abspath(os.path.join(root, file))
print "Modifying " + fullpath
i += 1
print str(i) + " files deleted";
elif sys.argv[1] == '--help':
# Show help message
showhelp()
else:
print "Argument must be a valid directory"
else:
showhelp()
答案 0 :(得分:3)
如果你的意思是拉丁字符而不是ASCII,那么regex
就是你的朋友:
s = u'汉语 / 漢語; Hànyǔ or 中文; Zhōngwén.tmp'
> print regex.sub(u'\p{^Latin}', u'_', s)
_________Hànyǔ_or_____Zhōngwén_tmp
> print regex.sub(u'\p{^Latin}+', u'_', s)
_Hànyǔ_or_Zhōngwén_tmp
> print '.'.join( regex.sub(u'\p{^Latin}+', u'_', t)
for t in s.rsplit('.', 1) )
_Hànyǔ_or_Zhōngwén.tmp
如果你想保留被替换的角色:
> print '.'.join( regex.subf(u'\p{^Latin}',
lambda m: '_%04x' % ord(m[0]),
t)
for t in s.rsplit('.', 1) )
_6c49_8bed_0020_002f_0020_6f22_8a9e_003b_0020Hànyǔ_0020or_0020_4e2d_6587_003b_0020Zhōngwén.tmp
可逆:
regex.subf('_([0-9a-f]{4})', lambda m: unichr(int(m[1], 16)), s)
答案 1 :(得分:1)
试试这个:
p = re.compile(r'[^A-Za-z0-9]')
filename = p.sub('_', filename)
例如:
>>> p.sub('_', 'this-is-it')
'this_is_it'
>>> p.sub('_', 'â ê bla bla bla')
'______bla_bla_bla'
答案 2 :(得分:1)
safe_fname = 'â ê bla bla bla'.encode("ascii","ignore")
(假设你的意思是ascii ...而不是拉丁语)