使用 Python 重命名多个文件
programmingpythonserver side programming更新于 2025/1/25 2:52:17
要在 Python 中重命名文件,请使用 os 模块的 rename() 方法。rename() 方法的参数是 source_address(旧名称)和 destination_address(新名称)。
安装和导入 OS 模块
要安装 OS 模块 −
pip install os
要导入 −
import os
使用 rename() 方法重命名多个文件
rename() 方法可轻松用于重命名多个文件 −
示例
import os # Function to rename multiple files def main(): i = 0 path="E:/amit/" for filename in os.listdir(path): my_dest ="new" + str(i) + ".jpg" my_source =path + filename my_dest =path + my_dest # rename() function will # rename all the files os.rename(my_source, my_dest) i += 1 # Driver Code if __name__ == '__main__': # Calling main() function main()
以上命令将重命名文件夹"amit"中的所有文件。
重命名特定的多个文件
在 Python 中,您可以选择要重命名文件夹中的哪些多个文件。
import os filesRename = ['demo_1.txt', 'demo_2.txt', 'demo_3.txt',] folder = r"E:\docs" # Iterate for file in os.listdir(folder): # Checking if the file is present in the list if file in filesRename: oldName = os.path.join(folder, file) n = os.path.splitext(file)[0] b = n + '_new' + '.txt' newName = os.path.join(folder, b) # Rename the file os.rename(oldName, newName) res = os.listdir(folder) print(res)
以上操作将仅重命名 docs 文件夹中的 3 个文件。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

