Python Problem...
Mates!!!
i have a problem with some .pdf files.. i want to rename them using python but when i read the directory and append them to a list.. it doesn’t get them as i wish..
Let me explain.. i have a folder with 240 pdf’s with names 1,2,3,4-240 and i want to rename them.. but when i append them to list it takes the first one then the 10th then 100th then 101 202 103..109 then 11th..
HAVE YOU GOT ANY IDEAS why and how to FIX it…???
```import os
path = “tttttttttt/1”
dirs = os.listdir(path)
file_list = []
for filenames in dirs:
if filenames.endswith(“.pdf”):
file_list.append(filenames)
print(file_list)```
B)
Use os.rename(src, dst) to rename or move a file or a directory.
```$ ls
cheese_cheese_type.bar cheese_cheese_type.foo
$ python
import os
for filename in os.listdir(“.”):
… if filename.startswith(“cheese_”):
… os.rename(filename, filename[7:])
…$ ls
cheese_type.bar cheese_type.foo```
Message me anytime!
B)
B)
The order in which you get the files from listdir probably depends on the OS you are using. If you look at the documentation, it tells you the order is arbitrary.
If you want to sort the list, you can indeed convert the names to integers first, but you have to take into account that the filenames are not just integers. Using int on something with ‘.pdf’ will indeed not work. First remove the extension, then convert it.
B.t.w., I don’t think there is any reason to sort the list, is there? The order in which you rename them doesn’t matter and the filename itself is enough to determine the target filename.
You can remove the extension first and use os.rename, use a for loop to apply that on all of your files.
I can create a C# program who does that if you want but I don’t use that much python.
Let me know if you want me to create it maybe it will be helpful to you in some way ?
Message me anytime!
Guys thank you very much! That’s a full team spirit!
dloser i want to sort them cause those pdf’s are like a degree and it’s one has a specific name in it, so i have another list with names so i’d like to put each name to each pdf..
DIDIx13 I’ve already done it using some excel knowledge plus command line. Thank you very much for the support!
“hack this” make me using it so now i wanna do everything with that!
Really i appreciated!!
B)
Just add
file_list.sort (key=int)
Before your loop. It will sort the list after passing each element to the int method. You would need to get rid of the extension first, you can do it prerty easily with map.
I am a bit lazy to comment this, but it should work:
file_list = list(filter(lambda s: s.count('.pdf') > 0, file_list))
file_list.sort(key=lambda s: int(s.replace('.pdf', ''))