简体   繁体   中英

Error in changing to directory using os.chdir in for loop - python

Hey i've got this script which converts all the flv video files in a directory to mp4 format.

I got it to work with just having all the files placed in one directory but am now needing to modify it so it goes into folders within that directory and converts the files within each folder it comes across.

Here is my code

sourcedirectory="/home/dubit/Desktop/test/"

class ConvertToMP4:
    def __init__(self):
        self.flvfiles = []

    def fetch_flv_files(self, directory_name):
        print("Scanning directory: " + directory_name)
        for (dirpath, dirnames, filenames) in os.walk(directory_name):
            for files in filenames:
                if files.endswith('.flv'):
                    print('convert file: ' + files)
                    self.flvfiles.append(files)

    def convert_flv_file_to_mp4_file(self):
        # check to see if the list is empty, if not proceed
        num_of_dir = len(list(os.walk(sourcedirectory)))
        if len(self.flvfiles) <= 0:
            print("No files to convert!")
            return
        for x in range(num_of_dir):
            for (dirpath, dirnames, filenames) in os.walk(sourcedirectory):
                for z in dirpath:
                    os.chdir(z)
                    for flvfiles in filenames:
                        mp4_file = flvfiles.replace('.flv','.mp4')
                        cmd_string = 'ffmpeg -i "' + flvfiles + '" -vcodec libx264 -crf 23 -acodec aac -strict experimental "' + mp4_file + '"'
                        print('converting ' + flvfiles + ' to ' + mp4_file)
                        os.system(cmd_string)


def main():
    usage = "usage: %prog -d <source directory for flv files>"
    parser = OptionParser(usage=usage)
    parser.add_option("-d","--sourcedirectory",action="store",
        type="string", dest="sourcedirectory", default="./",
        help="source directory where all the flv files are stored")
    (options, args) = parser.parse_args()
    flv_to_mp4 = ConvertToMP4()
    flv_to_mp4.fetch_flv_files(sourcedirectory)
    flv_to_mp4.convert_flv_file_to_mp4_file()
    return 0

main()

This is the error I am receiving

sudo ./sub_start_comp.py 
Scanning directory: /home/dubit/Desktop/test/
convert file: 20051210-w50s.flv
convert file: barsandtone.flv
Traceback (most recent call last):
File "./sub_start_comp.py", line 66, in <module>
    main()
File "./sub_start_comp.py", line 63, in main
  flv_to_mp4.convert_flv_file_to_mp4_file()
File "./sub_start_comp.py", line 46, in convert_flv_file_to_mp4_file
  os.chdir(z)
OSError: [Errno 2] No such file or directory: 'h'

I am new to python scripting so have not really got the knowledge to work out the issue so any help will be appreciated. If I had to take a guess its just taking the first character from the dirpath variable.

The dirpath is a single string. When you iterate over it using for loop ( for z in dirpath ), you're iterating over each individual character in string '/home/dubit/Desktop/test/' ! First z is set to '/' , then 'h' ... and that's where the chdir fails as there is no directory named h in your root directory.


Just replace

for z in dirpath:
    os.chdir(z)

with

os.chdir(dirpath)

and adjust indents accordingly, and it should work.

The error you're getting is due to the fact that dirpath is actually a string, not a list of strings. os.walk() returns a tuple, where dirpath being current directory being walked by, dirnames and filenames being dirpath 's contents.

Since a string is iterable in Python, you don't any interpreter errors, but instead you loop over each character in dirpath string. Like, for i, c in enumerate("abcd"): print('index: {i}, char: {c}'.format(i=i, c=c)) will output index: 0, char: a index: 1, char: b index: 2, char: c index: 3, char: d

So, you should chdir() to dirpath , not loop over it. Looping through the filesystem is done internally by os.walk() .

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