简体   繁体   English

重命名文件夹中的文件 - Python

[英]Rename files within a folder - Python

How can I rename files inside a folder without knowing their original name?如何在不知道原始名称的情况下重命名文件夹中的文件? For example I have a file.jpg and without knowing what it's called I want to call it test.jpg, this with all the files inside a folder.例如,我有一个 file.jpg,但不知道它叫什么,我想将其命名为 test.jpg,它包含一个文件夹中的所有文件。

Try this:尝试这个:

import os
import glob
# Getting all files in a folder (including hidden files)
files = os.listdir(os.path.expanduser("~/Downloads"))

# Getting all .jpg files in a directory
jpeg_files = glob.glob(os.path.expanduser("~/Downloads/*.jpeg"))

print(jpeg_files)
os.rename(jpeg_files[0], os.path.expanduser("~/Downloads/test.jpeg"))

If you want to rename all of the .jpeg files, then replace the last line with:如果要重命名所有.jpeg文件,请将最后一行替换为:

for file in jpeg_files:
    os.rename(file, os.path.expanduser("~/Downloads/test.jpeg"))

Right now I'm using os.expanduser() just so that it's easier for people to test现在我使用os.expanduser()只是为了让人们更容易测试

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

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