猿问

多个编辑文件无需更改'.DS_Store'

我正在尝试通过删除前 9 个字母来重命名多个文件,但是有一个名为“.DS_Store”的看不见的文件会出现错误。有什么办法可以避免该文件运行像'if...than...'之类的代码?代码就像:


import os


os.chdir('/Users/pgao/Google Drive/Piano Sheet/Be Our Guest')


for f in os.listdir():

        new_name = f[9:]

        os.rename(f, new_name)

该目录的列表是:


WechatIMG149.jpeg

.DS_Store

WechatIMG152.jpeg

WechatIMG148.jpeg

WechatIMG147.jpeg

WechatIMG151.jpeg

WechatIMG150.jpeg

WechatIMG146.jpeg

它上升错误为:


Traceback (most recent call last):

  File "ReEdit.py", line 10, in <module>

    os.rename(f, new_name)


FileNotFoundError: [Errno 2] No such file or directory: '.DS_Store' -> ''

谢谢。


萧十郎
浏览 161回答 2
2回答

DIEA

你可以试试endswith():for f in os.listdir():&nbsp; &nbsp; if f.endswith(".jpeg"):&nbsp; &nbsp; &nbsp; &nbsp; new_name = f[9:]&nbsp; &nbsp; &nbsp; &nbsp; os.rename(f, new_name)

Qyouu

def listdir(path):&nbsp; &nbsp; for fn in os.listdir(path):&nbsp; &nbsp; &nbsp; &nbsp; if not fn.startswith('.'):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; yield fn
随时随地看视频慕课网APP

相关分类

Python
我要回答