Edit a file name using Python

Asked

Viewed 672 times

2

I am working with hundreds of pdf files, I have to rename them with the folder name where they are allocated.

for example:

pasta
  |--- pastajoão
           |-- celular.pdf
  |--- pastamaria
           |-- caderno.pdf

has how to use python to edit the name of the files leaving this way?:

pasta
  |--- pastajoão
           |-- pastajoão_celular.pdf
  |--- pastamaria
           |-- pastamaria_caderno.pdf

I have this code here:

    import pathlib import Path
    import os
    import shutil
    path = Path('meu caminho')
    for dirss in os.listdir(path=path):
    print(dirss)
    sleep(1)

    for dirs,  sub, files in os.walk(path):
        for file_ in files:
            path = os.path.join(dirs, file_)
            shutil.move(path, path)

    try:
        for _,  in path.glob('*.pdf'):
            edit = os.listdir()
            _.rename(edit)
    except Exception:
        print('Nenhum arquivo PDF')

he returns me this error

    for _,  in path.glob('*.pdf'):
    TypeError: cannot unpack non-iterable PosixPath object

also if I use the function rename() he was going to rename the entire file, right?

someone could help me ? :)

  • 1

    Can you use Python to edit the name of the files by leaving it like this?: Yes, but there are errors in your code and I may be wrong, but I don’t think you tried to solve anything, but you just copied and pasted and you want someone to solve your problem, if you edit and show interest in something showing you want to learn I’ll be back to pass a solution

  • That’s just a piece of my code

  • I just need to edit the name of the files.

  • I did a lot of research and found nothing that could help me and my soutions went wrong too.

  • is that the above code does not demonstrate that it has any kind of knowledge about the language

  • @Guilhermefrançadeoliveira I edited my post

  • trying to help you posted below something that can give you the expected result, take a look and if solve your problem just mark the answers that are useful

  • The specific error is happening because you put a , in for _, in path.glob('*.pdf'): - alias, by convention, e m Python, usams _ with a variable name only if it is a "trash basket" - that is, a value that is provided by side effect in some function call and will not be used. In this case it is your path object that you want to rename - better give a real name to variable.

Show 3 more comments

2 answers

0


OPTION 1:

You can try something like:

import os
def change_file_name(sufix, path):
    for file in os.listdir(path):
        prefix = path.split("\\")[-1] + "_" #Armazena o nome da pasta atual
        if file.endswith(sufix) and not file.startswith(prefix):
            #Verifica se o arquivo tem o sufixo procurado e se o arquivo
            #não foi alterado anteriormente.
            os.rename(path + "\\" + file, path + "\\" + prefix + file)

    print(os.listdir(my_path))

sufix = ".pdf"
path = r"c:\my\choosed\path"

change_file_name(sufix, path)

Of course, then you can do your customization to suit the complexity of your system, but the basis to make a change would be +- this code above.

OPTION 2:

You play a 'father' folder and go mapping the files in the 'daughters' folders.

import os
def change_file_name(sufix, path):
    for files in os.walk(path):
        prefix = files[0].split("\\")[-1] + "_" #Armazena o nome da pasta atual

        for file in files[2]: #Passa arquivo por arquivo dentro da pasta
            if file.endswith(sufix) and not file.startswith(prefix):
                #Verifica se o arquivo tem o sufixo procurado e se o arquivo
                #não foi alterado anteriormente.
                os.rename(files[0] + "\\" + file, files[0] + "\\" + prefix + file)

        print(files,"\n")

sufix = ".pdf"
path = r"c:\my\choosed\parent\path"

change_file_name(sufix, path)

In this case, by your example

pasta
  |--- pastajoão
           |-- celular.pdf
  |--- pastamaria
           |-- caderno.pdf

You only need to pass the directory 'folder', because 'pastajoão' and 'pastamaria' would automatically pass in the function 'os.walk()', so you only pass the root directory (or parent) and the other directories will be mapped autonomously.

  • I made a few edits to make the code more complete. It gets a suffix to search, like ". pdf" for example. Also passes the directory in which you want to change the file.

  • 1

    hi the code did not edit the files it continues as are

  • I made an edit, putting two options. Could you confirm if it worked? Or if you presented an error?

  • 1

    thank you friend, function correctly

0

following your code I made this small modification

from pathlib import Path
import os

path = Path('diretorio')
try:
    for _ in path.glob('*.pdf'):
        new_name = os.path.basename(os.path.dirname(_))
        print(os.path.join(os.path.abspath(new_name), new_name))
        _.rename(f'{os.path.join(os.path.abspath(new_name), new_name)}_{os.path.basename(_)}')
except Exception as err:
    print(err)
    print('Nenhum arquivo PDF')

something I noticed that you’re using the import pathlib import Path and the right thing would be from pathlib import Path

  • hi Uilherme the code failed to edit the files

  • put the path to where the files are?

  • yes, I did

  • gives me the error that appeared to you, for here I made an emulation and corresponded with the result

  • if you can provide me with your operating system as well

  • it returned no error, simply did not edit the file

  • i am using Ubuntu 19

  • I did some testing it returned me that expected str, bytes or os.Pathlike Object, not tuple

  • So let’s try to find the problem first, you are using the full path of the type folder, /home/user/Documentos/pastadestino? or just a part? the files that grants permission to edit the files? if you can show what appears when you from ls -l in the folder you want to edit

  • the error you gave me says you can’t get a tuple, you’re probably putting some item in some tuple, I’ll think of something that shows the error where it comes from, but try to use a full path as said above path = Path('/home/user/Documentos/pastadestino')

Show 5 more comments

Browser other questions tagged

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