简体   繁体   English

使用python更改文件名

[英]Change the file name by using python

I would like to change the file name in the folder, there are jpg file but corrupted with product id number.我想更改文件夹中的文件名,有 jpg 文件但已损坏产品 ID 号。 I tried to rename it and delete the string after ".jpg" by using python, here is the code, but there is no any change.我尝试使用 python 重命名它并删除“.jpg”之后的字符串,这是代码,但没有任何变化。

Do you guys have any suggestion?你们有什么建议吗?

import os

path=input('C:\\Users\\pengoul\\Downloads\\Files\\PIC\\')    

def rename(path):

    for file in os.listdir(path):

        if file.endswith(".jpg@v=*"):
            print(file)

            newfile=file.split("@",1)[0]
        
            newName=file.replace(file,newfile)
                    
            os.rename(os.path.join(path,file),os.path.join(path,newName))
 
rename(path)

print("End")

Rename the file of one folder and delete the string after.jpg by using python.使用python重命名一个文件夹的文件并删除.jpg之后的字符串。

if you input path from user, python automatically use "\" instead of "\\" so you shouldn't use "\\" while input.如果您从用户输入路径,python 会自动使用“\”而不是“\\”,因此您在输入时不应使用“\\”。 So I suggest one of these two ways:所以我建议以下两种方式之一:

path = input("Input your Path: ")
# And the user entered this: 'C:\Users\pengoul\Downloads\Files\PIC'

or要么

path = 'C:\\Users\\pengoul\\Downloads\\Files\\PIC'

or要么

path = r'C:\Users\pengoul\Downloads\Files\PIC'

I hope that works for you.我希望这对你有用。 If not, make us aware of that!如果没有,请让我们意识到这一点!

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

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