使用Python脚本查找和重命名文件

2024-06-23 19:57:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我不熟悉Python编码,所以这里有个问题。我想找到任何扩展名为“无标题”的文件,例如jpg,indd,psd。然后将它们重命名为当天的日期。在

我试过以下方法:

import os

for file in os.listdir("/Users/shirin/Desktop/Artez"):
    if file.endswith("untitled.*"):
        print(file)

当我运行脚本时,什么都没有发生。在


Tags: 文件方法inimport编码forosusers
3条回答

在这种情况下,^{}函数可能更有用:

import glob

for file in glob.glob("/Users/shirin/Desktop/Artez/untitled.*"):
    print(file)

您的函数不会打印任何内容,因为名称中可能没有以.*结尾的文件。glob.glob()函数将为您执行文件扩展。在

然后,您可以使用此命令重命名文件,如下所示:

^{pr2}$

Python datetime对象可用于获取合适的时间戳。在

Python字符串比较器不支持通配符。您可以在文本中的任何位置搜索“untitled.”:

import os
    for file in os.listdir("/Users/shirin/Desktop/Artez"):
        if "untitled." in file:
            print(file)

请记住,这将包括在文件的任何位置有“untitled.”的任何文件。在

试试这种方法

import os
directoryPath = '/Users/shirin/Desktop/Artez'
lstDir = os.walk(directoryPath) 
for root, dirs, files in lstDir:
  for fichero in files:        
    (filename, extension) = os.path.splitext(fichero)
    if filename.find('untitle') != -1: # == 0 if starting with untitle
         os.system('mv '+directoryPath+filename+extension+' '+directoryPath+'$(date +"%Y_%m_%d")'+filename+extension)

相关问题 更多 >

    热门问题