简体   繁体   中英

How to make os.walk change current directory

My program is supposed to start at a path given and then move through that and its sub directories looking for jpegs and organizing them by date captured. My program is running into errors when it tries to open a file in a sub directory.It states the file can't be found and when I started printing the current directory I saw it wasn't in the sub directory. My code and the error are below. How can I get os.walk to change to the next sub directory? Thanks

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)

My error was:

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'

One thing you could do is change filename to include the directory using os.path.join like so filename = os.path.join(dirname, filename) . Or you could change the current directory to dirname using os.chdir(dirname) prior to opening the files. However, the latter method when using os.walk(".") is not recommended within the documentation . Because it won't change the directory and assumes the user won't either.

Note: If you pass a relative pathname, don't change the current working directory between resumptions of walk(). walk() never changes the current directory, and assumes that its caller doesn't either.

os.walk returns tuple: path to current dir, list of directories in current dir and list of files in current dir.

So what you need to open those files is this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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