0

I have a CSV file with a column called "id" and I have a directory with files.I would like to rename those files according to the values that are in the cells below the "id" column.

I have the following code:

import pandas as pd

import os

path = os.chdir('/Users/Utilizador/pythonProjects/files')

df = pd.read_csv('/Users/Utilizador/pythonProjects/todos-cantar-palavras.csv', encoding='utf8')

i = 0

for file in os.listdir(path):
    new_file_name = df['id']
    os.rename(file, new_file_name)
   
    i = i + 1

It returns the following error:

TypeError: rename: dst should be string, bytes or os.PathLike, not Series

I imagine it should be quite easy, but because I am giving the first steps all the help would be appreciated.

Thank you!

1 Answer 1

2

instead of df['id'] you need to write df['id'].iloc[i] because df['id'] will give you series of value i.e whole column instead of single value that why you are getting error

import pandas as pd

import os

path = os.chdir('/Users/Utilizador/pythonProjects/files')

df = pd.read_csv('/Users/Utilizador/pythonProjects/todos-cantar-palavras.csv', encoding='utf8')

i = 0

for file in os.listdir(path):
    new_file_name = df['id'].iloc[i]
    os.rename(path+'/'+file, path+'/'+new_file_name)
   
    i = i + 1
Sign up to request clarification or add additional context in comments.

1 Comment

That's it! Thank you @Kapil Musale. Also I added the file extension with new_file_name = df['id'].iloc[i]+'.pdf Best regards

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.