Lyux
Lyux

Reputation: 463

Rename Files without Extension

So I got a Directory Dir and in Dir there are three subdirectories with five Files each:

  1. Dir/A/ one,two,three,four,five.txt
  2. Dir/B/ one,two,three,four,five.txt
  3. Dir/C/ one,two,three,four,five.txt

As you can see there are four Files without extension and one with the .txtextension

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?

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")

Upvotes: 0

Views: 3339

Answers (2)

cs95
cs95

Reputation: 402473

Use os.walk if you want to perform recursive traversal.

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.

Upvotes: 4

inspectorG4dget
inspectorG4dget

Reputation: 113945

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)))

Upvotes: 0

Related Questions