我一直在编写一段代码来帮助我组织文件。经过深入的挖掘和对STACK的很好的询问,我得以(通过强制)学习了一些东西。
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:
我想知道如何将这些文件的目标的绝对路径附加到不是我现在设置的源中的副本中:)也作为即时消息,了解我的代码中是否有错误
答案 0 :(得分:-2)
此代码应该可以解决您的问题:
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中的C:\和Linux中的/
。但是我假设您已经知道如何将目录更改为您的首选文件夹。但是,如果您有任何疑问,请随时发表评论。
编辑: 对于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)