简体   繁体   English

使用 python 重命名文件夹中的文件名列表

[英]Rename a list of filename in a folder using python

I have a list of WAV files in a folder of data showing in the format of hours, minutes and second.我有一个数据文件夹中的 WAV 文件列表,以小时、分钟和秒的格式显示。

For example,例如,

C:\Users\Desktop\Data

01h02m02s.wav
01h02m13s.wav
01h02m24s.wav

I need the filename to be modified, programmatically such that it needs to be converted into seconds.我需要以编程方式修改文件名,以便将其转换为秒。 How do I do it?我该怎么做?

3722s.wav
3733s.wav
3744s.wav

Would appreciate all feedback and help.感谢所有反馈和帮助。

Thank you谢谢

Use glob.glob() to get your file list and then an regular expression to try and extract the hours , minutes and seconds from the filename.使用glob.glob()获取文件列表,然后使用正则表达式尝试从文件名中提取hoursminutesseconds os.rename() is used to actually rename the file: os.rename()用于实际重命名文件:

import glob
import re
import os

path = r'C:\Users\Desktop\Data'

for wav in glob.glob(os.path.join(path, '*.wav')):
    re_hms = re.findall(r'(\d+)h(\d+)m(\d+)s\.wav', wav)

    if re_hms:
        hours, minutes, seconds = map(int, re_hms[0])
        total_seconds = hours * 3600 + minutes * 60 + seconds
        new_wav = os.path.join(path, '{}s.wav'.format(total_seconds))
        print "{} -> {}".format(wav, new_wav)
        os.rename(wav, new_wav)

os.path.join() is used to safely join file paths together without having to worry about adding path separators. os.path.join()用于将文件路径安全地连接在一起,而不必担心添加路径分隔符。

You could use this if all the files in the path are WAV and their names have the pattern as shown by you.如果路径中的所有文件都是 WAV 并且它们的名称具有您显示的模式,则可以使用它。

import os

path = r'C:\Users\Desktop\Data'
waves = os.listdir(path)

for wave in waves:
    hours, minutes, seconds = map(int, [wave[:2], wave[3:5], wave[6:8]])
    total_seconds = hours * 3600 + minutes * 60 + seconds
    new_name = os.path.join(path, "{}s.wav".format(total_seconds))

    os.rename(os.path.join(path, wave), new_name)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM