David
David

Reputation: 19

Python: rename files from CSV

Problem

I have a list of words in different languages with their English translation:

#;Eng;Spanish;
1;yes;si;
2;no;ningun;
3;question;cuestión;

For all these words (or entries), I have an audio file on how to pronounce the word (from Forvo). The audio files are named with language and the "#" value. Thus, spanish1.m4a, spanish2.m4a, spanish3.m4a, etc.

Now, I want to rename that file as follows: yes-si-1.m4a

Script

import pandas as pd
import os

os.chdir('/Users/user/Desktop/audio')

df = pd.read_csv('hebrew.csv', delimiter=';')

Row = (df['#']) #line number
Eng = (df['Eng']) #English trans
HebF = (df['HebF']) #Feminine
HebM = (df['HebM']) #Masculine

for filename in os.listdir():

oldName = os.path.basename(filename)

num = oldName.strip('hebrew')

Now I thought something with an If statement. If Row equals Num, then change the file name to Eng+HebF+Row+".m4a"

How do I solve this issue?

Upvotes: 1

Views: 546

Answers (2)

Jan Christoph Terasa
Jan Christoph Terasa

Reputation: 5935

Please make a backup of your file(s) before you try this

Why use Python or even pandas is you can just use awk:

awk -F ';' '{ if($1!="#") system("mv spanish"$1".m4a "$2"-"$3"-"$1".m4a") }' list.csv

This will rename your spanish#.m4a files according to your rule. You can apply the same to your hebrew problem.

Upvotes: 0

jfaccioni
jfaccioni

Reputation: 7509

You're in the right direction. Two main things to fix are:

  • In order to rename a file in programming, you generally move them to the same folder, using different names. This can be easily done with the shutil module of Python's standard library.
  • Try to keep it simple for yourself. No need to change directories and build absolute paths for your files - simply leave your python script in the same folder as the files you want to rename, open a terminal in that folder and execute the script. Python is able to see files which are in the same folder just by passing the file name, no need for a full path.

The following code does what you want for the spanish csv example in your OP, renaming the files spanish1.m4a, spanish2.m4a and spanish3.m4a. Note that:

1) all files (code, csv and .m4a files) should be in the same directory;

2) I'm using f-strings for building the file name strings - hopefully the formatting is obvious enough from the code;

3) You'll need to do some refactoring in order for the code to work with your files in other languages.

Using pandas is overkill for this task but I didn't want to change your code structure too much. Let me know if you have any doubts.

import pandas as pd
import shutil

df = pd.read_csv('spanish.csv', delimiter=';')

Row = (df['#']) #line number
Eng = (df['Eng']) #English trans
Spa = (df['Spanish']) #Spanish 

for i in Row:
    eng = Eng[i-1]
    spa = Spa[i-1]
    old_file = f"spanish{i}.m4a"
    shutil.move(old_file, f"{eng}-{spa}-{i}.m4a")

Upvotes: 1

Related Questions