2014-03-06 9 views
0

특정 문자열로 시작하는 파일을 찾은 다음 새 디렉토리로 이동하는 간단한 함수를 만들려고하는데 다음과 같은 종류의 오류가 계속 발생합니다. "IOError : [Errno 2 ] 해당 파일이나 디렉토리가 없습니다 : '18 -1.pdf ' ", 파일이 존재하더라도.shutil이있는 파일 이동 중 오류가 발생했습니다.

import os 
import shutil 
def mv_files(current_dir,start): 
    # start of file name 
    start = str(start) 
    # new directory ro move files in to 
    new_dir = current_dir + "/chap_"+ start 
    for _file in os.listdir(current_dir): 
     # if directory does not exist, create it 
     if not os.path.exists(new_dir): 
       os.mkdir(new_dir) 
     # find files beginning with start and move them to new dir 
     if _file.startswith(start): 
      shutil.move(_file, new_dir) 

나는 셔터를 잘못 사용합니까?

올바른 코드 : 당신이 shutil.move의 전체 경로를 포기하지 않을 것 같은

import os 
import shutil 
def mv_files(current_dir,start): 
    # start of file name 
    start = str(start) 
    # new directory ro move files in to 
    new_dir = current_dir + "/chap_" + start 
    for _file in os.listdir(current_dir): 
     # if directory does not exist, create it 
     if not os.path.exists(new_dir): 
      os.mkdir(new_dir) 
     # find files beginning with start and move them to new dir 
     if _file.startswith(start): 
      shutil.move(current_dir+"/"+_file, new_dir) 

답변

2

것 같습니다. 시도 :

if _file.startswith(start): 
    shutil.move(os.path.abspath(_file), new_dir) 

을이 실패하면, os.getcwd()의 결과와 함께 _filenew_dir 인쇄 및 답변에 추가하려고합니다.

+0

덕분에 파일 이름과 전체 경로 만 알려주고 있다는 사실을 간과했습니다. –