每日一问—01如何在指定目录下的文件名前面加上“0”+序号

约 168 字小于 1 分钟...

每日一问—01如何在指定目录下的文件名前面加上“0”+序号

python版本

import os
path = "C:\\"
i = 1
for filename in os.listdir(path):
    try:
        new_name = "0" + str(i) + "_" + filename
        os.rename(os.path.join(path, filename), os.path.join(path, new_name))
        i += 1
    except PermissionError:
        print("拒绝访问路径,请启用超级权限")

C++版本

#include <iostream>
#include <filesystem>
#include <string>
 
namespace fs = std::filesystem;
 
int main() {
    std::string path = "C:\\";
    int i = 1;
 
    for (const auto& entry : fs::directory_iterator(path)) {
        try {
            std::string filename = entry.path().filename().string();
            std::string new_name = "0" + std::to_string(i) + "_" + filename;
            fs::rename(entry.path(), entry.path().parent_path() / new_name);
            i++;
        }
        catch (const std::exception& e) {
            std::cout << "Error: " << e.what() << std::endl;
        }
    }
 
    return 0;
}
已到达文章底部,欢迎留言、表情互动~
  • 赞一个
    0
    赞一个
  • 支持下
    0
    支持下
  • 有点酷
    0
    有点酷
  • 啥玩意
    0
    啥玩意
  • 看不懂
    0
    看不懂
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.2