2016-05-17 91 views
0

我的程序應該從給定的路徑開始,然後通過它和它的子目錄尋找jpegs並按捕獲日期組織它們。我的程序在試圖打開子目錄中的文件時出現錯誤。它聲明文件無法找到,當我開始打印當前目錄時,我看到它不在子目錄中。我的代碼和錯誤如下。我怎樣才能讓os.walk變成下一個子目錄?由於如何使os.walk改變當前目錄

import os 
import exifread 
from datetime import datetime 

class Image(object): 
    name = "" 
    dateTakem = "" 

    # The class "constructor" - It's actually an initializer 
    def __init__(self, name, dateTaken): 
     self.name = name 
     self.dateTaken = dateTaken 

def makeImage(name, dateTaken): 
    img = Image(name, dateTaken) 
    return img 

def formatDateTime(imageDt): 
    d = datetime.strptime(imageDt, '%Y:%m:%d %H:%M:%S') 
    dateStr = d.strftime('%Y:%m:%d') 
    return dateStr 

#path = raw_input("Please enter path name: ") 
path="/Users/Me/Pictures/Litmas"#For faster testing 
if not os.path.exists(path): 
    print ("Input path does not exist. Path is being created..") 
    try: 
     os.makedirs(path) 
    except (IOError, OSError) as exception: 
     print ("Path could not be created") 
    else: 
     print ("Success! Path has been created") 
os.chdir(path) 
count=0 
unique=0 
uniList=[] 
imgList=[] 
cwd = os.getcwd() 
print (cwd) 
for (dirname, dirs, files) in os.walk('.', topdown=False): 
    imgList[:]=[] 
    uniList[:]=[] 
    print (imgList) 
    print (uniList) 
    for filename in files: 
     #Checks if it is a JPEG 
     if filename.endswith('.jpg') or filename.endswith('.JPG') or filename.endswith('.JPEG') or filename.endswith('.jpeg'): 
      print ("\n"+filename) 
      #Adds 1 for every picture processed 
      count+=1 
      cwd = os.getcwd() 
      print (cwd) 
      #opens jpeg for exifread 
      f = open(filename, 'rb') 
      #Gets all the tags needed 
      tags = exifread.process_file(f, details=False) 
      #Goes through tags to find date captured 
      for tag in tags.keys(): 
       #Converts date object to string 
       dtStr=str(tags['EXIF DateTimeOriginal']) 
       #Strips time so it is just date 
       fDate = formatDateTime(dtStr) 
       fDate=fDate.replace(":","-") 
      print (fDate) 
      #Creates Image instance 
      newImg=makeImage(filename,fDate) 
      #Adds date to list for unique 
      uniList.append(fDate) 
      #Adds image instance to list for images 
      imgList.append(newImg) 
    uniList=list(set(uniList)) 
    unique+=len(uniList) 
    print ("Destination folders will be created with these filenames: ") 
    print (uniList) 
    #for folder in uniList: 
     #current=os.getcwd() 
     #newPath=current+"/"+folder 
     #try: 
      #os.makedirs(newPath) 
     #except (IOError, OSError) as exception: 
      #print ("Path could not be created") 
    #for image in imgList: 
     #filename=image.name 
     #dateDest=image.dateTaken 
     #current=os.getcwd() 
     #newDest=current+"/"+dateDest+"/"+filename 
     #currDest=current+"/"+filename 
     #os.rename(currDest, newDest) 

print ("Total JPEGs Processed: ") 
print(count) 
print ("Total Unique Dates Processed: ") 
print(unique) 

我的錯誤是:

Traceback (most recent call last): 

File "./Challenge.py", line 56, in <module> 

    f = open(filename, 'rb') 

IOError: [Errno 2] No such file or directory: 'DSC_0063.jpg' 
+0

'filename'只是給出了文件名而不是整個路徑,嘗試'F =開放(os.path.join(根,文件名) ,'rb')' –

回答

0

有一件事你可以做的是改變filename包括使用os.path.join像這樣filename = os.path.join(dirname, filename)的目錄。或者您可以在打開文件之前使用os.chdir(dirname)將當前目錄更改爲dirname。但是,在documentation中不推薦使用os.walk(".")時的後一種方法。因爲它不會更改目錄並假定用戶不會。

注:如果你傳遞一個相對路徑,不改變行走的復會的當前工作目錄()。 walk()永遠不會更改當前目錄,並且假定其調用者不會。

0

os.walk返回元組路徑:當前目錄的路徑,當前目錄中的目錄列表以及當前目錄中的文件列表。

所以,你需要打開這些文件,這是什麼:

f = open(os.path.join(dirname, filename), 'rb')