python - 提取目录中的文件夹名称列表后,如何使用 Python 将它们重命名为另一种格式?
问题描述
我想清理我的文件,并且在提取目录中的文件夹列表后目前卡住了。我想提取文件夹的日期部分并根据这些日期生成 .txt 文件。
下面我使用的代码:
import os
root ="C:\\Users\\Mr. Slowbro\\Desktop\\Test Python\\"
dirlist = [ item for item in os.listdir(root) if os.path.isdir(os.path.join(root, item)) ]
print (dirlist)
输出如下列表:
['20 年 1 月 1 日 - Alpha'、'9 月 8 日 - Bravo'、'18 年 12 月 31 日 - 收据文件夹']
如何获得以下输出并将它们生成为另一个文件夹中的 .txt 文件?
例如。
20 年 1 月 1 日.txt
19 年 9 月 8 日.txt
12 月 31 日 18.txt
解决方案
据我了解,我们需要.txt
为每个与问题中的名称相称的目录名称创建一个文件。
我们可以拆分每个目录-
并构建文件名,例如:
import os
target_dir = "path\\to\\directory\\"
for _dir in dirlist:
filename = _dir.split("-")[0].strip() + ".txt" # get the date and add extension
filepath = os.path.join(target_dir, filename)
with open(filepath, "w") as f: pass # create file
推荐阅读
- javascript - 为什么这个 ASP.NET Web 处理程序没有收到 POST 请求?
- java - Java HashMap 不会插入重复项
- html - React Hook useEffect 缺少依赖项:
- django - Websocket 只能在同一网络内发送和接收消息。(Elasticbeanstalk(linux2) 和 elasticache 上的 Django3 频道 3)
- selenium - 如何通过终端运行 TestNG.xml 文件
- regex - HH:MI:SS 字符串返回秒数
- spring-boot - 使用 Spring Boot 应用程序和 Keycloak 授权访问资源属性
- apache - SVN / Apache 问题未定义符号:apr_crypto_block_cleanup
- javascript - 如果包含破折号,则 jQuery 中输入数字的值返回空字符串
- java - 如何排除通过@JsonAppend 添加的属性