


How to change a file named with ID number to a name using Python?
Using Python scripts to realize batch renaming of ID number files to names
In practical applications, we often need to process files named after the ID number and rename them to the corresponding name. This article provides an efficient Python solution that combines Excel table data to realize batch file renaming.
Suppose you have an Excel file (such as "data.xls") that contains the ID number and name correspondence, and a folder that contains the files named after the ID number. The following code will help you complete file renaming:
Original code and existing problems:
The following code tries to change the file from ID number to name based on the mapping relationship in Excel table, but there are efficiency and robustness issues:
import os import pandas as pd df = pd.read_excel("data.xls") id_list = os.listdir("./") for id_file in id_list: id_num = id_file[:id_file.find(".")] ext = id_file[id_file.find("."):] name = df[df["ID number"] == id_num].name.values print(name) if len(name) != 0: name = name[0] print(f"Start rename: {id_file} -> {name}{ext}") os.rename(id_file, name ext) print("Rename ends")
The main problem with this code is that it searches Excel files multiple times, which is inefficient. When there are too many files, performance will drop sharply.
Improved Python code:
To improve efficiency and robustness, we adopt a more direct traversal method:
import os import pandas as pd df = pd.read_excel("data.xls") id_name_map = dict(zip(df["ID card number"], df["Name"])) # Create a mapping dictionary of ID number to name id_list = os.listdir("./") for id_file in id_list: id_num = id_file[:id_file.find(".")] ext = id_file[id_file.find("."):] if id_num in id_name_map: new_name = id_name_map[id_num] ext print(f"Start rename: {id_file} -> {new_name}") os.rename(id_file, new_name) print("Rename ends")
This code first creates a mapping dictionary of ID number to name, then iterates over the file list and searches the corresponding name through the dictionary, thus avoiding repeated searches of Excel table data and significantly improving efficiency. In addition, it also shows the logic of the code more clearly.
With the above improvements, you can more effectively implement batch file renaming and improve work efficiency. Please make sure that the "data.xls" file exists in the same directory as the Python script, and that the "ID number" and "Name" column names are the same as the column names in the Excel file.
The above is the detailed content of How to change a file named with ID number to a name using Python?. For more information, please follow other related articles on the PHP Chinese website!

Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.

ArraysarecrucialinPythonimageprocessingastheyenableefficientmanipulationandanalysisofimagedata.1)ImagesareconvertedtoNumPyarrays,withgrayscaleimagesas2Darraysandcolorimagesas3Darrays.2)Arraysallowforvectorizedoperations,enablingfastadjustmentslikebri

Arraysaresignificantlyfasterthanlistsforoperationsbenefitingfromdirectmemoryaccessandfixed-sizestructures.1)Accessingelements:Arraysprovideconstant-timeaccessduetocontiguousmemorystorage.2)Iteration:Arraysleveragecachelocalityforfasteriteration.3)Mem

Arraysarebetterforelement-wiseoperationsduetofasteraccessandoptimizedimplementations.1)Arrayshavecontiguousmemoryfordirectaccess,enhancingperformance.2)Listsareflexiblebutslowerduetopotentialdynamicresizing.3)Forlargedatasets,arrays,especiallywithlib

Mathematical operations of the entire array in NumPy can be efficiently implemented through vectorized operations. 1) Use simple operators such as addition (arr 2) to perform operations on arrays. 2) NumPy uses the underlying C language library, which improves the computing speed. 3) You can perform complex operations such as multiplication, division, and exponents. 4) Pay attention to broadcast operations to ensure that the array shape is compatible. 5) Using NumPy functions such as np.sum() can significantly improve performance.

In Python, there are two main methods for inserting elements into a list: 1) Using the insert(index, value) method, you can insert elements at the specified index, but inserting at the beginning of a large list is inefficient; 2) Using the append(value) method, add elements at the end of the list, which is highly efficient. For large lists, it is recommended to use append() or consider using deque or NumPy arrays to optimize performance.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment
