2017-09-14 8 views
0

이 코드는 프로그램을 작성한 첫 시도입니다. 읽는 중에 오류가 발생합니다.디렉토리의 모든 파일을 다른 디렉토리로 가져 오는 방법은 무엇입니까? 코드를 작성했지만 예외가 발생했습니다

무엇이 잘못 되었나요? 이 프로그램의 목표는 모두 Excel, PDF, Word 파일을 가져 와서 프로그램에서 만든 폴더에 넣는 것입니다.

import os 
from glob import glob 

# import cx_Freeze 
print("Digite o diretório de origem.") 
dirOrigem = input() 

os.chdir(dirOrigem) 

excel_files = glob('*.xlsx') 
excel_files.append(''.join(glob('*.xls'))) 

dirDestinoXL = dirOrigem + '\\' + 'Planilhas Excel' 
if not os.path.exists(dirDestinoXL): 
    os.makedirs(dirDestinoXL) 

for i in excel_files: 
    os.rename(f'{dirOrigem}\\{"".join(i)}', f'{dirDestinoXL}\\{"".join(i)}') 

os.chdir(dirOrigem) 

pdf_files = glob('*.pdf') 

dirDestinoPDF = dirOrigem + '\\' + 'PDF' 
if not os.path.exists(dirDestinoPDF): 
    os.makedirs(dirDestinoPDF) 

for p in pdf_files: 
    os.rename(f'{dirOrigem}\\{"".join(p)}', f'{dirDestinoPDF}\\{"".join(p)}') 


os.chdir(dirOrigem) 

word_files = glob('*.doc') 
word_files.append(glob('*.docx')) 

dirDestinoWord = dirOrigem + '\\' + 'Word' 
if not os.path.exists(dirDestinoWord): 
    os.makedirs(dirDestinoWord) 

for d in word_files: 
    os.rename(f'{dirOrigem}\\{"".join(d)}', f'{dirDestinoWord}\\{"".join(d)}') 
+0

다른 프로세스에서 열려있는 파일이 있으면 해당 파일을 닫은 다음 다시 시도하십시오. – Antimony

+0

excel_files = glob ('* .xlsx') excel_files.append (''. join (glob ('*. xls'))) 'excel_files에 올바른 Excel 파일이 예상대로 포함되어 있습니까? 빈 목록 일 수 있습니다. – deaspo

+0

이것을 제거하십시오 : excel_files.append (''. join (glob ('*. xls'))) 잘 작동합니다. 빈 섹션을 추가하면 목록이 [ '']처럼 보이고 for 루프는 수정할 수없는 ''을 수정하려고 시도합니다. –

답변

1

에 내가 프로그램을 시도하고 내 컴퓨터에있는대로 작동하지 않습니다. 몇 줄을 바꿔서 작동합니다. 도움이 되었기를 바랍니다.

import os 
from glob import glob 

dirOrigem = r'C:\Users\fchal\Desktop\temp' # here I changed the code just because I didn't want to bother using input() 
os.chdir(dirOrigem) 

excel_files = glob('*.xlsx') 
excel_files.extend(glob('*.xls')) 


dirDestinoXL = dirOrigem + '\\' + 'xlsfile' 
if not os.path.exists(dirDestinoXL): 
    os.makedirs(dirDestinoXL) 

for i in excel_files: 
    os.rename(i, os.path.join(dirDestinoXL, i)) 


# same procedure for pdf and word files 
+0

이것은 흥미로운 것 같습니다. 내가 내 PC에서 그것을 실행하지 않을거야 입력을 넣어 그리고 난 그녀의 PC에 올바른 디렉토리가 필요합니다. 그러나 나는 그녀의 PC 디렉토리를 얻는다고 생각한다. –

0

나는 glob 가끔 엉망이 될 수 있음을 알고 있습니다. 파일이 열려 있으면 오류가 발생할 수 있습니다.

import os 

def move_files_with_extension(from_dir, to_dir, *extensions): 
    if not os.path.isdir(from_dir): 
     raise ValueError('{} is not a real directory'.format(from_dir)) 
    elif not os.path.isdir(to_dir): 
     raise ValueError('{} is not a real directory'.format(to_dir)) 

    files_with_extensions = all_files_with_extensions_in(from_dir, *extensions) 

    for file_path in files_with_extensions: 
     os.rename(file_path, os.path.join(to_dir, os.path.basename(file_path))) 

def all_files_with_extensions_in(dir, *extensions): 
    files_with_extensions = list() 

    for dir_path, dir_names, file_names in os.walk(dir): 
     for file_name in file_names: 
      if file_name.endswith(extensions): 
       files_with_extensions.append(os.path.join(dir_path, file_name)) 

    return files_with_extensions 

을 다음을 수행 할 수 있습니다 : 여기에 내가 어떻게 할 것인지의

dirOrigem = input() 

excel_location = os.path.join(dirOrigem, 'Planilhas Excel') 

move_files_with_extension(dirOrigem, excel_location, '.xls', '.xlsx') 

+0

이것은 정말 멋진 것입니다. 나는 아직도 모든 것이 어떻게 작동 하는지를 이해할 수 없다. 이것은 좋은 코드라고 불리는 것이며 사람들은 나쁜 코드라고 부르는 것입니까? 말하기에 문제 없습니다, 이것이 내 첫 번째 프로그램입니다. –

+0

롤! 당신의 코드가 좋지 않거나 제 코드가 좋다고하지는 않을 것입니다. 동일한 문제에 대한 다른 해결책. –