我一直在研究一段代码来帮助我组织文件。经过大量的挖掘和堆栈非常好的提问块,我能够(通过强制)学习一些东西。
def chkdir(d):
pathsrc = os.path.abspath(d) #absolute path to each file
fileparts = d.split('_')
fileparts[2] = fileparts[2].replace('.mov', '')
clipPath = os.path.join(postvispath, fileparts[0],fileparts[1], fileparts[2])
if os.path.exists(clipPath):
print 'True: Path Exists, Ignoring'
skiplist.append("%s"%tdy+" "+pathsrc)
else:
print 'False: Creating Path'
transferlist.append("%s"%tdy+" "+pathsrc)
try:
os.makedirs(clipPath)
shutil.copyfile(pathsrc, '%s/%s' %(clipPath, pathsrc.split('/')[-1]))
print
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
我想知道如何附加目标的绝对路径,这些文件将被复制到源而不是我现在设置的源:) 也正在学习我的代码中是否有任何错误
此代码应该可以解决您的问题:
import os
import shutil
#lets say that the extension is mp4 but you can change it to the correct one
file_name = 'RRR_0010_V001.mp4'
file_name_parts = file_name.split('_')
#remove the extension for the last folder in the dir
file_name_parts[2] = file_name_parts[2].replace('.mp4', '')
directory = os.path.join(file_name_parts[0],file_name_parts[1],file_name_parts[2])
try:
os.makedirs(directory)
except FileExistsError:
with open('errors.log', 'a') as log:
log.write('Error: File already exists.')
shutil.copy(file_name,directory)
这应该根据您的文件名创建一个目录并将原始文件复制到那里。但默认情况下,这在主目录中有效,例如 Windows 和/
Linux 中的C:\ 。但我假设您已经知道如何将目录更改为您的首选文件夹。但是,如果您有任何疑问,请随时发表评论。
编辑:对于 cwd 中的所有文件,代码大致相同。
import os
import shutil
#lets say that the extension is mp4 but you can change it to the correct one
def make_dir_with_file(file_name):
file_name_parts = file_name.split('_')
#remove the extension for the last folder in the dir
file_name_parts[2] = file_name_parts[2].replace('.mp4', '')
directory = os.path.join(file_name_parts[0],file_name_parts[1],file_name_parts[2])
try:
os.makedirs(directory)
except FileExistsError:
with open('errors.log', 'a') as log:
log.write('Error: File already exists.')
shutil.copy(file_name,directory)
for file in os.listdir(os.getcwd()):
make_dir_with_file(file)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句