Rename files and move out of the Python directory

Asked

Viewed 450 times

1

i am developing a python script, which he needs to access a folder and within that folder has 3 folders which has several files

example:

Pastaprincipal
    |
    | ---- pasta1
             | ---- arquivo.pdf
    |
    | ---- pasta2
             | ---- arquivo.pdf
    |
    | ---- pasta3
             | ---- arquivo.pdf

what I need to do and rename these acquisitions of extension PDF and then remove them from the folders by moving to the PastaPrincipal.

being like this

   Pastaprincipal
    |
    | ---- pasta1
    |
    | ---- pasta2
    |
    | ---- pasta3
    | ---- renomeado.pdf
    | ---- renomeado.pdf
    | ---- renomeado.pdf

here is my code

import os
from time import sleep

def Files(filepath):
    print('Lendo a pasta principal [{pasta}]...'.format(pasta=os.path.basename(filepath)))
    sleep(1)
    for files in os.listdir(path=filepath):
        print(files)
        os.chdir(files)
if __name__ == '__main__':
    filess = input('deretório principal:')
    Files(filess)

when I use the os.chdir() so I can enter inside the folders it returns me an error FileNotFoundError: [WinError 2] The system cannot find the file specified: 'pasta1'.

what I want to do is rename before I can move the files.

Can someone please help me :)

3 answers

0


os.chdir is a bad approach to working with files in multiple folders, why the current directory is changed - and your program has to know "where it is".

The best is always working with the directory names along with the file names, everywhere - changing the directory as we do in the terminal will be headache. Up to Python 3.5, to join the directory with the file name, the most recommended was to use os.path.join - the program gets big.

From Python 3.6 onwards, the pathlib library has been perfected and can do a lot of cool things in file manipulation - basically you use an object of the type pathlib.Path instead of a string with a file name or directory - and this is an object that has a lot of different methods - including an equivalent to os.listdir and a .rename - in addition to one that searches for arches in subdirectories by type.

What’s more - in all modern operating systems, the method that renames a file is the even that moves it to another directory - so it doesn’t make sense for you to rename it to move it later.

With the structure you put in the example, you can do something like:

from pathlib import Path

principal = Path("Pastaprincipal")


for contador, pdf_path in enumerate(principal.glob("**/*.pdf")):
    novo_nome = principal / f"renomeado{contador:02d}.pdf"
    pdf_path.rename(novo_nome)

(To / with the Path object creates another Path indicating the file within a directory, the same as in the terminal - the enumerate just enjoy the for and generates a sequence of numbers, so that each file has a unique name)

This code assumes that you will run the program from a folder above the "Main Folder" - if you want it to work from anywhere, put the absolute path to this folder. If you want it to work from the folder where you are when calling the program on the terminal, (Iss and, you do cd Pastaprincipal in the terminal and calls the program), change it to start in the current directory with principal = Path(".")

  • Thanks for the help, it worked obriagdo

  • if it worked, consider marking this answer as accepted - you can still vote for other answers you think are cool.

0

I tested your code in a directory on my machine (Macosx) and for me it worked normally to enter the folders I have in this directory. So I couldn’t replicate the error. I just had to check if the file is actually a directory. My code got like this, I just didn’t try to move the directory files:

import os
from time import sleep

def Files(filepath):
    print('Lendo a pasta principal [{pasta}]...'.format(pasta=os.path.basename(filepath)))
    sleep(1)
    for files in os.listdir(path=filepath):
        print(os.getcwd()+"/"+files)
        if os.path.isdir(os.getcwd()+"/"+files):
            print(files)
            os.chdir(os.getcwd()+"/"+files)
filess = input('diretório principal:')
Files(filess)

Regarding the error specifically, it seems to be a Windows error when it is not able to find the directory you specified. So I really can’t replicate. Try to see if you are typing the directory correctly, if it really exists, and if there is a different way to specify the directory on your operating system. In this thread(in English), they explain what to do when you have this mistake.

  • HI Thiago thanks man, for I renown the files continued inside the folders I will use the os.Rename(), listing the files and then rename them.

0

The mistakes you’re having may be for some reason that we won’t be able to test, but you should use error treatments to prevent them

Follow a small modification I already performed by renaming and moving the files to the destination location

import os
from time import sleep


def Files(filepath):
    print('Lendo a pasta principal [{pasta}]...'.format(pasta=os.path.basename(path=filepath)))
    sleep(1)
    BASE = os.path.abspath(path=filepath)
    n = 1
    for files in os.listdir(path=BASE):
        if os.path.isdir(path=os.path.join(BASE, files)):
            print(files)
            for file in os.listdir(path=os.path.join(BASE, files)):
                print(file)
                if os.path.isfile(path=os.path.join(BASE, files, file)):
                    try:
                        os.rename(src=os.path.join(BASE, files, file), dst=os.path.join(BASE, 'New_name({}).pdf'.format(n)))
                        n += 1
                    except Exception as err:
                        print('Arquivo nao pode ser renomeado e movido pelo erro: {}'.format(err))


if __name__ == '__main__':
    filess = input('deretório principal:')
    Files(filess)

Tip

If you are using python 3.5 above, you can change the use of .format() to the f strings leaving more elegant

and if you use python 3.8 (Most current version so far) you can use the new := I will put what your code would look like if you used the latest version

import os
from time import sleep


def Files(filepath):
    print(f'Lendo a pasta principal [{os.path.basename(filepath)}]...')
    sleep(1)
    BASE = os.path.abspath(path=filepath)
    n = 1
    for files in os.listdir(path=BASE):
        if os.path.isdir(path=files):
            print(files)
            for file in os.listdir(path=(fs := os.path.join(BASE, files))):
                print(file)
                if os.path.isfile(f := os.path.join(fs, file)):
                    try:
                        os.rename(src=f, dst=os.path.join(BASE, f'New_name({n})'))
                        n += 1
                    except Exception as err:
                        print(f'Arquivo nao pode ser renomeado e movido pelo erro: {err}')


if __name__ == '__main__':
    filess = input('deretório principal:')
    Files(filess)
  • hi William, it returns me this error Rename() Missing required argument 'dst'

  • Tests here and find no error, checked if you put the above code correctly? , strange you get this error being that this argument is in the above code, I’ll change a few things that might solve, only about 5 min

  • Check now, and if you happen to become a bug, if you can let me know the version running Python and try to copy the code from this https://onlinegdb.com/rkTRBmbAH

  • Thank you for your help William worked.

  • nothing, and do not forget to put and mark all the answers that were useful and relevant S2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.