2016-03-02 87 views
0

我是Python编程的新手,所以这里有一个问题。我想找到任何类型的扩展名为“无标题”的文件,例如JPG,INDD,PSD。然后将它们重命名为当天的日期。使用Python脚本查找和重命名文件

我曾尝试以下:

import os 

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

当我运行该脚本,没有任何反应。

+0

尽量不要你的意思是'如果file.startswith( “无题”)'? – zondo

回答

1

您可能会发现glob功能在这种情况下更加有用:因为有可能没有在名称中.*结尾的文件

import glob 

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

你的功能不显示任何信息。 glob.glob()函数将为您执行文件扩展。

然后,您可以使用该做你的文件重命名如下:

import glob 
import os 
from datetime import datetime 

current_day = datetime.now().strftime("%Y-%m-%d") 

for source_name in glob.glob("/Users/shirin/Desktop/Artez/untitled.*"): 
    path, fullname = os.path.split(source_name) 
    basename, ext = os.path.splitext(fullname) 
    target_name = os.path.join(path, '{}{}'.format(current_day, ext)) 
    os.rename(source_name, target_name) 
0

Python字符串比较不支持通配符。您可以搜索“无标题”。文本中的任意位置:

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

请记住,这将包括任何具有“未命名”的文件。在文件的任何位置。

0

这种方法

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) 
0
import os 

for file in os.listdir("/Users/shirin/Desktop/Artez"): 
    if(file.startswith("untitled")): 
     os.rename(file, datetime.date.today().strftime("%B %d, %Y") + "." + file.split(".")[-1])