Python을 사용하여 디렉터리의 여러 파일 이름 바꾸기
한 디렉터리의 여러 파일 이름을 바꾸는 작업은 수동으로 수행할 경우 지루한 작업이 될 수 있습니다. 그러나 Python은 이 프로세스를 자동화하여 더욱 효율적이고 정확하게 만드는 여러 옵션을 제공합니다.
접근 방식:
os.path.split 사용
import os folder = 'dir' files = os.listdir(folder) for file in files: # Split the filename and extension filename, ext = os.path.splitext(file) # Modify the filename modified_filename = filename.split('_')[1] # Combine the modified filename with the extension new_file = modified_filename + ext # Rename the file os.rename(os.path.join(folder, file), os.path.join(folder, new_file))
문자열 조작 사용:
import os folder = 'dir' files = os.listdir(folder) for file in files: if file.startswith('CHEESE_'): # Remove 'CHEESE_' from the filename new_file = file[7:] # Rename the file os.rename(os.path.join(folder, file), os.path.join(folder, new_file))
os.rename 사용
import os folder = 'dir' files = os.listdir(folder) for file in files: if file.startswith('CHEESE_'): # Get the new filename new_file = file[7:] # Use os.rename() to change the filename os.rename(os.path.join(folder, file), os.path.join(folder, new_file))
모두 이러한 접근 방식을 사용하면 디렉터리에서 파일 이름을 바꾸고 "CHEESE_" 접두사를 제거하고 원래 확장자를 유지하는 원하는 결과를 얻을 수 있습니다.
위 내용은 Python을 사용하여 디렉터리에 있는 여러 파일의 이름을 바꾸는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!