2017-01-06 2 views
0

그래서 내가 파일 목록의 이름을 변경하기 위해 노력하고있어 :이름 바꾸기 여러 파일

import os 
import time 
for fileName in os.listdir("."): 
    os.rename(fileName, fileName.replace("0001", "00016.5")) 
    os.rename(fileName, fileName.replace("0002", "00041")) 
    os.rename(fileName, fileName.replace("0003", "00042")) 
... 

를하지만 나에게이 오류 os.rename(fileName, fileName.replace("0002", "00041"))``OSError: [Errno 2] No such file ordirectory (파일이 디렉토리에) 그래서

을 제공합니다 다음으로

import os 
import time 
for fileName in os.listdir("."): 
    os.rename(fileName, fileName.replace("0001", "00016.5")) 
for fileName in os.listdir("."): 
    os.rename(fileName, fileName.replace("0002", "00041")) 
for fileName in os.listdir("."): 
    os.rename(fileName, fileName.replace("0003", "00042")) 
... 

을 시도하지만 내가 잘못 여기서 뭘 메신저 추가 문자에 많은 매우 이상하게 파일을 이름을 변경?

+2

당신이'0001라는 이름의 파일 이름을 변경하려고 '0016.5','0002'에서'00041'까지 파일명 등으로 처리하거나 다른 작업을 수행합니까? – NPE

+1

SAME 파일의 이름을 순차적으로 변경합니다. 물론 첫 번째 이름을 변경 한 후에 원본 파일이 더 이상 존재하지 않으므로 오류가 발생합니다. – Andrey

+0

당신이'0004'에 도착했을 때 제공되는 것보다 더 많은 remamings을 가지고 있다면'0003'이'00042'로 이름을 바꾸고'0004'가 포함되기 때문에 더 많은 것을 가질 것입니다 – WhatsThePoint

답변

1

단일 패스 이름 바꾸기 중에 다중 패스 이름 바꾸기가 작동한다는 사실은 파일 중 일부에 0001 패턴과 0002 패턴이 포함되어 있다는 것을 의미하지 않습니다.

그래서 하나의 루프를 수행 할 때, 당신은 파일의 이름을 변경하고 있지만 파일의 이전 목록 (listdirlist 반환, 그래서 당신이 파일의 이름을 변경 자마자 오래된 것) =>를 일부 소스 파일이 될 수 없습니다를 제공하고 있습니다 녹이다.

다중 패스로 작업 할 때 일부 파일에 여러명의 이름이 적용됩니다. 일 (보다 컴팩트) 수

: 그것은 (이것은 이전의 반복에서 이름이 변경되었습니다 의미) 존재하지 않는 경우

for fileName in os.listdir("."): 
    for before,after in (("0001", "00016.5"),("0002", "00041"),("0003", "00042")): 
     if os.path.exists(fileName): 
      newName = fileName.replace(before,after) 
      # file hasn't been renamed: rename it (only if different) 
      if newName != fileName: 
       os.rename(fileName,newName) 

기본적으로 내가 파일의 이름을 변경하지 않습니다. 따라서 가능한 한 개의 이름을 바꿀 수 있습니다. 당신은 단지 어느 것을 우선 순위해야합니다.

1

listdir은 전체 경로가 아닌 모든 객체의 이름 (파일, 디렉토리 등)을 반환합니다. os.path.join()을 사용하여 전체 경로를 생성 할 수 있습니다. 루프가 이름 변경에 대한 당신의, 00,041에 먼저 00016.5 발견 된 모든 객체, ... 파일의 이름을 변경하는

한 가지 방법은 다음과 같은 수 있습니다 :

import os 
import time 

currentDir = os.pathdirname(__file__) 
for fileName in os.listdir(currentDir): 
    if '0001' in fileName: 
     oldPath = os.path.join(currentDir, fileName) 
     newPath = os.path.join(currentDir, fileName.replace("0001", "00016.5")) 
    elif '0002' in fileName: 
     oldPath = os.path.join(currentDir, fileName) 
     newPath = os.path.join(currentDir, fileName.replace("0002", "00041")) 
    else: 
     continue 

    os.rename(oldPath, newPath) 
관련 문제