如何使os.walk更改当前目录

时间:2016-05-17 17:13:50

标签: python

我的程序应该从给定的路径开始,然后遍历该子程序及其子目录,查找jpeg并按捕获的日期组织它们。我的程序在尝试打开子目录中的文件时遇到错误。它表示找不到该文件,当我开始打印当前目录时,我看到它不在子目录中。我的代码和错误如下。如何让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'

2 个答案:

答案 0 :(得分:0)

您可以做的一件事是更改filename以使用os.path.join包含目录,如filename = os.path.join(dirname, filename)。或者,您可以在打开文件之前使用dirname将当前目录更改为os.chdir(dirname)。但是,documentation中不推荐使用os.walk(".")时的后一种方法。因为它不会改变目录并假定用户也不会。

  

注意:如果传递相对路径名,请不要在walk()的恢复之间更改当前工作目录。 walk()从不更改当前目录,并假定其调用者也不会。

答案 1 :(得分:0)

os.walk返回元组:当前目录的路径,当前目录中的目录列表以及当前目录中的文件列表。

那么打开这些文件需要的是:

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