Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function that similar to bash find command

Tags:

python

I have a dir structure like the following:

[me@mypc]$ tree .
.
├── set01
│   ├── 01
│   │   ├── p1-001a.png
│   │   ├── p1-001b.png
│   │   ├── p1-001c.png
│   │   ├── p1-001d.png
│   │   └── p1-001e.png
│   ├── 02
│   │   ├── p2-001a.png
│   │   ├── p2-001b.png
│   │   ├── p2-001c.png
│   │   ├── p2-001d.png
│   │   └── p2-001e.png

I would like to write a python script to rename all *a.png to 01.png, *b.png to 02.png, and so on. Frist I guess I have to use something similar to find . -name '*.png', and the most similar thing I found in python was os.walk. However, in os.walk I have to check every file, if it's png, then I'll concatenate it with it's root, somehow not that elegant. I was wondering if there is a better way to do this? Thanks in advance.

like image 357
clwen Avatar asked Nov 23 '11 18:11

clwen


People also ask

Can I use bash commands in Python?

Execute an existing bash script using Python subprocess module. We can also execute an existing a bash script using Python subprocess module.

What does %% bash do in Python?

This command will give you the core project you are working on. The export command in bash is used to set values to environmental variables. In the case it basically sets the value of an environmental variable called PROJECT and the echo just echoes the value back to the console.

Is find a bash command?

The Bash find command in Linux offers many ways to search for files and directories. In this tutorial, you'll learn how a file's last-time access, permissions, and more can help find files and directories with the Bash find command.


2 Answers

For a search pattern like that, you can probably get away with glob.

from glob import glob
paths = glob('set01/*/*.png')
like image 153
Michael Mior Avatar answered Nov 16 '22 00:11

Michael Mior


You can use os.walk to traverse the directory tree. Maybe this works?

import os

for dpath, dnames, fnames in os.walk("."):
  for i, fname in enumerate([os.path.join(dpath, fname) for fname in fnames]):
    if fname.endswith(".png"):
      #os.rename(fname, os.path.join(dpath, "%04d.png" % i))
      print "mv %s %s" % (fname, os.path.join(dpath, "%04d.png" % i))

For Python 3.4+ you may want to use pathlib.glob() with a recursive pattern (e.g., **/*.png) instead:

  • Recursively iterate through all subdirectories using pathlib
  • https://docs.python.org/3/library/pathlib.html#pathlib.Path.glob
  • https://docs.python.org/3/library/pathlib.html#pathlib.Path.rglob
like image 25
moooeeeep Avatar answered Nov 16 '22 01:11

moooeeeep