如何重命名文件(使用Python OS模块)?
我有一个文件夹,其中包含+100歌曲,名为“歌曲名称,歌手名称”(例如Smooth Firster,Michael Jackson )。我正在尝试将所有歌曲重命名为“歌曲名称(歌手名称)”(例如Smooth Primits(Michael Jackson))。
我尝试了此代码。但是,我不知道要写哪些参数。
import os
files = os.getcwd()
os.rename(files, "") # I'm confused because I don't know what to put here as parameters since I want to change only parts of the files' names, and not the files' names entirely.
关于“ os.rename()”参数有什么建议吗?
I have a folder which contains +100 songs named this way "Song Name, Singer Name" (e.g. Smooth Criminal, Michael Jackson). I'm trying to rename all the songs to "Song Name (Singer Name)" (e.g. Smooth Criminal (Michael Jackson)).
I tried this code. But, I didn't know what parameters to write.
import os
files = os.getcwd()
os.rename(files, "") # I'm confused because I don't know what to put here as parameters since I want to change only parts of the files' names, and not the files' names entirely.
Any suggestions on the parameters of "os.rename()"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
与命令行程序
重命名
可以使用单个命令中的模式重命名的文件批次,Python的os.rename()
是围绕基础重命名 syscall。因此,它可以一次重命名一个文件。
假设所有歌曲都存储在同一目录中,并以'.mp3'之类的扩展名结尾,则一种方法是循环循环
os.listdir()
。此外,明智的做法是检查当前文件是否确实是文件,而不是目录或符号链接。可以使用
os.path.isfile()
这是一个完整的示例:
Note :如果这些歌曲可能存储在子文件夹中,则)将比较低级别
os.listdir()
更好Unlike the command line program
rename
which can rename a batch of files using a pattern in a single command, Python'sos.rename()
is a thin wrapper around the underlyingrename
syscall. It can thus rename a single file at a time.Assuming all songs are stored in the same directory and ends with an extension like '.mp3', one approach is to loop over the return of
os.listdir()
.Additionally, it would be wise to check that current file is, indeed a file and not, say, a directory or symbolic link. This can be done using
os.path.isfile()
Here is a full example:
Note: If the songs are potentially stored in subfolders,
os.walk()
will be a better candidate than the lower levelos.listdir()
我建议您使用OS编写循环。
但是,使用Pandas,您可以毫无问题地替换一些名字狙击,我建议您为此任务选择Pandas!
I would recommend you to write a loop using os.
However with pandas you can replace some Name snipeds with no problem, I would recommend chosing pandas for this Task!