2016-08-24 2 views
0

안녕하세요, 디렉토리에있는 모든 flv 비디오 파일을 mp4 형식으로 변환하는이 스크립트가 있습니다.for 루프 - 파이썬에서 os.chdir을 사용하여 디렉토리로 변경하는 중 오류가 발생했습니다.

모든 파일이 하나의 디렉토리에 배치되었지만 이제는 해당 파일을 수정해야 해당 디렉토리 내의 폴더로 이동하여 각 폴더 내의 파일을 변환합니다. 여기

이 내가 수신하고있는 오류가 내 코드

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() 

입니다

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' 

그래서 정말 그렇게 도움이 문제를 해결하기 위해 지식을 가지고하지 않은 내가 파이썬 스크립팅에 새로운 오전 감사하겠습니다. dirpath 변수에서 첫 번째 문자를 가져온다 고 추측해야만한다면.

+0

'dirpath'는 문자열입니다. 왜 너는 그걸 왜 반복하고 있니? –

답변

4

dirpath단일 문자열입니다. for 루프 (for z in dirpath)를 사용하여 반복 할 때 문자열 '/home/dubit/Desktop/test/'의 각 개별 문자를 반복합니다! 처음으로 z'/'으로 설정되고 'h' ...이고 루트 디렉토리에 h 디렉토리가 없으므로 chdir이 실패합니다.


그냥

os.chdir(dirpath) 

for z in dirpath: 
    os.chdir(z) 

을 대체하고 그에 따라 들여 쓰기를 조정하고, 그것을 작동합니다.

+0

고맙습니다. 미래에 대해 알기에 유용하고 그에 따라 일하고 있습니다. –

1

오류는 dirpath이 실제로 문자열이며 문자열 목록이 아니기 때문에 발생합니다. os.walk()은 터플을 반환합니다. dirpath은 현재 디렉토리가 dirnames이고 filenamesdirpath의 내용입니다.

문자열은 파이썬에서 반복 가능하기 때문에 해석기 오류는 발생하지 않지만 각 문자는 dirpath 문자열로 반복됩니다. 마찬가지로, for i, c in enumerate("abcd"): print('index: {i}, char: {c}'.format(i=i, c=c)) 출력됩니다 index: 0, char: a index: 1, char: b index: 2, char: c index: 3, char: d

그래서, 당신이해야 chdir()dirpath에, 그 위에하지 루프. 파일 시스템 루핑은 내부적으로 os.walk()에 의해 수행됩니다.

+0

지식에 감사드립니다. –

관련 문제