디렉토리에서 파일의 이름을 바꾸는 배치
-
03-07-2019 - |
문제
Python을 사용하여 디렉토리에 이미 포함 된 파일 그룹의 이름을 바꾸는 쉬운 방법이 있습니까?
예시: *.doc 파일로 가득 찬 디렉토리가 있으며 일관된 방식으로 이름을 바꾸고 싶습니다.
x.doc-> "new (x) .doc"
y.doc-> "new (y) .doc"
해결책
예를 들어 이러한 이름을 변경하는 것은 매우 쉽습니다 OS 그리고 글로벌 모듈 :
import glob, os
def rename(dir, pattern, titlePattern):
for pathAndFilename in glob.iglob(os.path.join(dir, pattern)):
title, ext = os.path.splitext(os.path.basename(pathAndFilename))
os.rename(pathAndFilename,
os.path.join(dir, titlePattern % title + ext))
그런 다음 다음과 같은 예에서 사용할 수 있습니다.
rename(r'c:\temp\xx', r'*.doc', r'new(%s)')
위의 예는 모두 변환합니다 *.doc
파일 c:\temp\xx
DIR new(%s).doc
, 어디 %s
파일의 이전 기본 이름입니다 (확장자없이).
다른 팁
나는보다 일반적이고 복잡한 코드를 만드는 대신해야 할 각 교체마다 작은 하나의 라이너를 작성하는 것을 선호합니다. 예 :
이것은 모든 밑줄을 현재 디렉토리의 숨겨지지 않은 파일의 하이픈으로 대체합니다.
import os
[os.rename(f, f.replace('_', '-')) for f in os.listdir('.') if not f.startswith('.')]
정규 표현식을 사용하지 않는다면이 기능은 파일 이름을 바꿀 때 많은 전력을 제공합니다.
import re, glob, os
def renamer(files, pattern, replacement):
for pathname in glob.glob(files):
basename= os.path.basename(pathname)
new_filename= re.sub(pattern, replacement, basename)
if new_filename != basename:
os.rename(
pathname,
os.path.join(os.path.dirname(pathname), new_filename))
따라서 예에서는 할 수 있습니다 (파일이있는 현재 디렉토리라고 가정) :
renamer("*.doc", r"^(.*)\.doc$", r"new(\1).doc")
그러나 초기 파일 이름으로 롤백 할 수도 있습니다.
renamer("*.doc", r"^new\((.*)\)\.doc", r"\1.doc")
그리고 더.
폴더의 하위 폴더에서 모든 파일 이름을 바꾸는 것만으로도 있습니다.
import os
def replace(fpath, old_str, new_str):
for path, subdirs, files in os.walk(fpath):
for name in files:
if(old_str.lower() in name.lower()):
os.rename(os.path.join(path,name), os.path.join(path,
name.lower().replace(old_str,new_str)))
나는 Old_str의 모든 발생을 New_str의 경우에 따라 대체하고 있습니다.
노력하다: http://www.mattweber.org/2007/03/04/python-script-renamepy/
나는 음악, 영화 및 사진 파일이 특정 방식으로 이름을 붙이는 것을 좋아합니다. 인터넷에서 파일을 다운로드하면 일반적으로 이름 지정 컨벤션을 따르지 않습니다. 나는 내 스타일에 맞게 각 파일을 수동으로 이름을 바꾸는 것을 발견했습니다. 이것은 정말 빨리 늙어 갔기 때문에 나는 그것을 위해 그것을하기 위해 프로그램을 작성하기로 결정했습니다.
이 프로그램은 파일 이름을 모든 소문자로 변환하고, 파일 이름의 문자열을 원하는대로 교체하고, 파일 이름의 전면 또는 뒷면에서 여러 문자를 다듬을 수 있습니다.
프로그램의 소스 코드도 사용할 수 있습니다.
나는 스스로 파이썬 스크립트를 썼습니다. 파일이 존재하는 디렉토리의 경로와 사용하려는 이름 지정 패턴의 인수로 인수가 필요합니다. 그러나 증분 번호 (1, 2, 3 등)를 귀하가 제공하는 이름 패턴에 첨부하여 이름을 바꿉니다.
import os
import sys
# checking whether path and filename are given.
if len(sys.argv) != 3:
print "Usage : python rename.py <path> <new_name.extension>"
sys.exit()
# splitting name and extension.
name = sys.argv[2].split('.')
if len(name) < 2:
name.append('')
else:
name[1] = ".%s" %name[1]
# to name starting from 1 to number_of_files.
count = 1
# creating a new folder in which the renamed files will be stored.
s = "%s/pic_folder" % sys.argv[1]
try:
os.mkdir(s)
except OSError:
# if pic_folder is already present, use it.
pass
try:
for x in os.walk(sys.argv[1]):
for y in x[2]:
# creating the rename pattern.
s = "%spic_folder/%s%s%s" %(x[0], name[0], count, name[1])
# getting the original path of the file to be renamed.
z = os.path.join(x[0],y)
# renaming.
os.rename(z, s)
# incrementing the count.
count = count + 1
except OSError:
pass
이것이 당신을 위해 효과가 있기를 바랍니다.
directoryName = "Photographs"
filePath = os.path.abspath(directoryName)
filePathWithSlash = filePath + "\\"
for counter, filename in enumerate(os.listdir(directoryName)):
filenameWithPath = os.path.join(filePathWithSlash, filename)
os.rename(filenameWithPath, filenameWithPath.replace(filename,"DSC_" + \
str(counter).zfill(4) + ".jpg" ))
# e.g. filename = "photo1.jpg", directory = "c:\users\Photographs"
# The string.replace call swaps in the new filename into
# the current filename within the filenameWitPath string. Which
# is then used by os.rename to rename the file in place, using the
# current (unmodified) filenameWithPath.
# os.listdir delivers the filename(s) from the directory
# however in attempting to "rename" the file using os
# a specific location of the file to be renamed is required.
# this code is from Windows
비슷한 문제가 있었지만 디렉토리의 모든 파일의 파일 이름의 시작 부분에 텍스트를 추가하고 비슷한 방법을 사용하고 싶었습니다. 아래 예를 참조하십시오 :
folder = r"R:\mystuff\GIS_Projects\Website\2017\PDF"
import os
for root, dirs, filenames in os.walk(folder):
for filename in filenames:
fullpath = os.path.join(root, filename)
filename_split = os.path.splitext(filename) # filename will be filename_split[0] and extension will be filename_split[1])
print fullpath
print filename_split[0]
print filename_split[1]
os.rename(os.path.join(root, filename), os.path.join(root, "NewText_2017_" + filename_split[0] + filename_split[1]))
이름 변경을 수행 해야하는 디렉토리에 있어야합니다.
import os
# get the file name list to nameList
nameList = os.listdir()
#loop through the name and rename
for fileName in nameList:
rename=fileName[15:28]
os.rename(fileName,rename)
#example:
#input fileName bulk like :20180707131932_IMG_4304.JPG
#output renamed bulk like :IMG_4304.JPG
내 디렉토리에 나에게 여러 개의 서브 디어가 있고, 각 하위 디어에는 모든 이미지를 1.jpg ~ n.jpg로 변경하려는 많은 이미지가 있습니다.
def batch_rename():
base_dir = 'F:/ad_samples/test_samples/'
sub_dir_list = glob.glob(base_dir + '*')
# print sub_dir_list # like that ['F:/dir1', 'F:/dir2']
for dir_item in sub_dir_list:
files = glob.glob(dir_item + '/*.jpg')
i = 0
for f in files:
os.rename(f, os.path.join(dir_item, str(i) + '.jpg'))
i += 1
(Mys 자신의 답변)https://stackoverflow.com/a/45734381/6329006
# another regex version
# usage example:
# replacing an underscore in the filename with today's date
# rename_files('..\\output', '(.*)(_)(.*\.CSV)', '\g<1>_20180402_\g<3>')
def rename_files(path, pattern, replacement):
for filename in os.listdir(path):
if re.search(pattern, filename):
new_filename = re.sub(pattern, replacement, filename)
new_fullname = os.path.join(path, new_filename)
old_fullname = os.path.join(path, filename)
os.rename(old_fullname, new_fullname)
print('Renamed: ' + old_fullname + ' to ' + new_fullname
이 코드는 작동합니다
이 함수는 파일 이름을 바꾸는 경로로 F_PATTH를 정확하게, 파일의 새 이름으로 New_Name을 정확하게 가져옵니다.
import glob2
import os
def rename(f_path, new_name):
filelist = glob2.glob(f_path + "*.ma")
count = 0
for file in filelist:
print("File Count : ", count)
filename = os.path.split(file)
print(filename)
new_filename = f_path + new_name + str(count + 1) + ".ma"
os.rename(f_path+filename[1], new_filename)
print(new_filename)
count = count + 1