繁体   English   中英

根据 excel sheet-PYTHON 中可散列的文件名重命名目录中的文件

[英]Renaming files in the directory based on file names hashable in the excel sheet-PYTHON

我正在创建一个 python 脚本来重命名所有文件。

在此处输入图像描述

我将文件保存为这些数字,现在打开它并命名它们太麻烦了,所以我想为它创建一个脚本。 我有一张 excel 表,它代表文件的名称 w.r.t 它的编号。

在此处输入图像描述

我必须先清洁 excel。 在这里,由于重复,excel 表中不存在某些数字,并且我们不知道目录中重复的 state,因此不会触及这些数字。

在此处输入图像描述

我认为散列会在这里帮助我,但我面临一些错误。 请帮帮我。 这是我的代码

import pandas as pd
data=pd.read_excel(r'C:\Users\Kirti\Downloads\Book2.xlsx')
data=data[:-1]
data['Number']=data['Number'].astype(int)
hs=data.set_index('Number')['Name'].to_dict()
count=1
import os 
os.chdir(r'C:\Users\Kirti\Documents\Notnumbered')
for f in os.listdir(r'C:\Users\Kirti\Documents\Notnumbered'):
    try:
        file_name='{}.{}'.format(count,'pdf')
        new_name = '{}.{}'.format(hs[count], 'pdf')
        print(file_name,new_name)
        os.rename(f, new_name)
    except KeyError: 
        count+=1
        continue
    count+=1

错误:

1.pdf ITILST0701 Transition Planning and Support Policy.pdf     # If we see here, the counter didn't 
                                                              #increase and name of the file
                                                              # stayed the first name only. 
---------------------------------------------------------------------------
FileExistsError                           Traceback (most recent call last)
<ipython-input-6-5f40d4caed55> in <module>
      7         new_name = '{}.{}'.format(hs[count], 'pdf')
      8         print(file_name,new_name)
----> 9         os.rename(f, new_name)
     10     except KeyError:
     11         count+=1

FileExistsError: [WinError 183] Cannot create a file when that file already exists: '127.pdf' -> 'ITILST0701 Transition Planning and Support Policy.pdf'

为什么计数器不增加? 如果编译了 127 之前的文件,那么应该已经打印出来了。 提前致谢

错误FileExistsError显示具有此名称的文件已存在。

所以你应该抓住这个错误来继续代码

    except FileExistsError: 

喜欢

import os   # PEP8: all imports at the beginnig

count = 1   # PEP8: spaces around `=`

os.chdir(r'C:\Users\Kirti\Documents\Notnumbered')

for f in os.listdir():  # if you already do `chdir` then you don't have to use full path
    try:
        file_name = '{}.pdf'.format(count)
        new_name = '{}.pdf'.format(hs[count])

        print(file_name, new_name)  # PEP8: space after `,`

        os.rename(f, new_name)
    except KeyError as ex: 
        print('KeyError:', ex)  # it is good to display message with error - to see if there was some problem
    except FileExistsError as ex: 
        print('FileExistsError:', ex)  # it is good to display message with error - to see if there was some problem

    count += 1

或者您应该检查文件是否已经存在并仅在不存在时重命名

    if not os.path.exists(new_name):
        os.rename(f, new_name)

喜欢:

import os   # PEP8: all imports at the beginnig

count = 1   # PEP8: spaces around `=`

os.chdir(r'C:\Users\Kirti\Documents\Notnumbered')

for f in os.listdir():  # if you already do `chdir` then you don't have to use full path
    try:
        file_name = '{}.pdf'.format(count)
        new_name = '{}.pdf'.format(hs[count])

        print(file_name, new_name)  # PEP8: space after `,`

        if not os.path.exists(new_name):
            os.rename(f, new_name)
        else:
            print('File already exists')
    except KeyError as ex: 
        print('KeyError:', ex)  # it is good to display message with error - to see if there was some problem

    count += 1

PEP 8 -- Python 代码的样式指南

暂无
暂无

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

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