Home > Blockchain >  Rename files based on csv file values - Python
Rename files based on csv file values - Python

Time:06-16

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!

CodePudding user response:

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
  • Related