简体   繁体   English

重命名不带扩展名的文件

[英]Rename Files without Extension

So I got a Directory Dir and in Dir there are three subdirectories with five Files each: 所以我有一个目录DirDir有三个子目录,每个子目录有五个文件:

  1. Dir/A/ one,two,three,four,five.txt Dir / A /一,二,三,四,五.txt
  2. Dir/B/ one,two,three,four,five.txt Dir / B /一,二,三,四,五.txt
  3. Dir/C/ one,two,three,four,five.txt Dir / C /一,二,三,四,五.txt

As you can see there are four Files without extension and one with the .txt extension 如您所见,有四个不带扩展名的文件和一个带.txt扩展名的文件

How do I rename all Files without extension in a recursive manner? 如何以递归方式重命名所有不带扩展名的文件?

Currently I'm trying this, which works for a single Directory, but how could I catch all Files if I put this Script into Dir ? 目前,我正在尝试此方法,该方法仅适用于单个目录,但是如果将此脚本放入Dir ,如何捕获所有文件?

import os, sys

for filename in os.listdir(os.path.dirname(os.path.abspath(__file__))):
    base_file, ext = os.path.splitext(filename)
    if ext == "":
        os.rename(filename, base_file + ".png")

Use os.walk if you want to perform recursive traversal. 如果要执行递归遍历,请使用os.walk

for root, dirs, files in os.walk(os.path.dirname(os.path.abspath(__file__))):
    for file in files:
        base_path, ext = os.path.splitext(os.path.join(root, file))

        if not ext:
            os.rename(base_path, base_path + ".png")

os.walk will segregate your files into normal files and directories, so os.path.isdir is not needed. os.walk会将您的文件分为正常的文件和目录,因此不需要os.path.isdir

import os

my_dir = os.getcwd()
for root, dirnames, fnames in os.walk(my_dir):
    for fname in fnames:
        if fname.count('.'): continue  # don't process a file with an extension
        os.rename(os.path.join(root, fname), os.path.join(root, "{}.png".format(fname)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM