Python-用下划线替换所有空格并将目录中所有文件转换为小写

标签 python

我正在尝试按照标题说明进行操作,但收到了消息
WinError2:无法使用下面的代码片段找到指定的文件 'New Text Document.txt' -> 'new_text_document.txt'。是的,我的桌面位于驱动器号 D 上,这假定目标目录名为“目录”。我在名为“New Text Document.txt”的目录中有一个示例文件。我只是不知道问题出在哪里。

import os
path = 'D:\Desktop\directory'
filenames = os.listdir(path)
for filename in filenames:
    os.rename(filename, filename.replace(' ', '_').lower())

最佳答案

使用列表理解的单线:

import os

directory = 'D:\Desktop\directory'

[os.rename(os.path.join(directory, f), os.path.join(directory, f).replace(' ', '_').lower()) for f in os.listdir(directory)]

从答案 Batch Renaming of Files in a Directory 借来的列表理解

关于Python-用下划线替换所有空格并将目录中所有文件转换为小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43728163/

相关文章:

python - 如何为特定的 Python 类启用解码?

python - 在 flask 中运行破折号应用程序

python - boost-python 当 C++ 方法返回 std::map<string,X*>

python - 使用混合数据类型优化 Tensorflow 数据管道

python - 如何正确地将unicode字符写入文件

python - 是否可以限制 Python 中条件列表理解的长度?

python - 如何在 Mountain Lion 上安装 MySQLdb

python - 在 AWS EC2 linux 中运行 selenium webdriver

java - 来自 Java Runnable 的 Py4J 回调

python - 如何在 Visual Studio Code 中设置 Python 语言特定的制表符间距?