Rename Matching Items in Python

77 Views Asked by At

I am trying to rename files in using a list. here is a dumbed down version of the code I am building.

import os, sys, numpy
data = os.listdir(r"C/names/")
pdfs= ['123-fox.pdf','111-max.pdf','333-ok.pdf','145-somthin.pdf','666-abc.pdf','674-box.pdf','222-alpha.pdf']
new_names = ['123','111','333','666','888','101']

for x in os.listdir(data):
    if x in pdfs:
        try:
            if any(item in x for item in pdfs):
                new = os.rename(str(pdfs),str(new_name))
                print(new)
            else: 
                print('no')
        except FileNotFoundError:
            print('no')

I think I am miss understanding the matching abilities with Python. This returns the following. It does rename the files one at a time, but it does not match it with the string that is intended.

[WinError 123] The filename, directory name, or volume label syntax is incorrect: 

The goal would be to get this:

--> C/names/123.pdf

--> C/names/111.pdf

etc...

EDIT

import os, sys, glob, pandas as pd, numpy as np, re, ctypes
data = (r"N:\\Home\\")
excel = "excel.xlsx"
#in the excel sheet, what is the string for the column name that is being used? 
ColumnName = 'File Num'


list1 = [p for p in os.listdir(data) if p.endswith('.pdf') is True]
#print(list1)
old_name = [os.path.join(data+y) for y in list1]
#print(old_name)
list2 = [x for x in pd.read_excel(str(data)+excel, dtype=str)[ColumnName].tolist() if pd.notnull(x)]
#print(list2)
new_name = [os.path.join(data,y+'.pdf') for y in list2]
#print(new_name)
matching = [s for s in list1 if any(p in s for p in list2)]
#print(matching)

for old_name,new_name in zip(old_name,new_name):
    if old_name == new_name:
        os.rename(old_name,new_name)
    else:
        print('no')

'''

0

There are 0 best solutions below