我已经浏览过之前关于此错误的帖子。但是,这对我没有帮助。所以我重新提请注意。代码如下。
import os
replacements = {':': '_', '+': '_'}
for fn in os.walk('/media/ambijat/Dataworld/f23/Dropbox/ttgis'):
nn = fn
for k, v in replacements.items():
nn = nn.replace(str(k), str(v))
if nn != fn:
os.rename(fn, nn)
这在运行时给出错误 'tuple' object has no attribute 'replace'似乎出错了。我正在使用 dict 替换文件名中的特殊字符,例如 [,&<>*?|\";+:'() ] .有没有更好的方法来做到这一点。谢谢。
请您参考如下方法:
os.walk产生元组:
For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).
要仅提取文件名,请使用索引或序列解包。这些中的任何一个都可以工作:
nn = fn[-1]
nn = fn[2]
_, _, nn = fn
或者,正如@AntonvBR 指出的那样,您可以在可迭代的for 循环定义中使用序列解包:
for _, _, fn in os.walk('/media/ambijat/Dataworld/f23/Dropbox/ttgis'):
nn = fn
# as before..
