这是编写将PDF文件移动到新文件夹的程序的最短,最有效的方法吗?

时间:2018-09-12 10:15:35

标签: python

编码新手,阅读一些书籍并尝试练习。在python3.7中编写程序,以搜索目录找到所有pdf文件,然后将它们移动到名为“阅读材料”的新文件夹

如何改进此代码,例如python中更短,更简洁和/或更有效的脚本?

import os, re, shutil

os.chdir(r'C:\\Users\\Luke\\Documents\\coding\\python\\') #set cwd to the where I want program to run

#create regex to identify pdf files
PDFregex = re.compile(r'''^(.*?)  # all text before the file extension
                          \.{1}   #start of file extension
                          (pdf)$  #ending in pdf''', re.VERBOSE)

Newdir = os.mkdir('Reading Material') #make new directory for files
NewdirPath = os.path.abspath('Reading Material')
print('new directory made at : '+NewdirPath)

#search through directory for files that contain .pdf extension using regex object
for pdf in os.listdir('.'):
    mo = PDFregex.search(pdf)
    if mo == None: #no pdf's found by regex search
        continue    #bypass loop
    else:
        originalLoc = os.path.join(os.path.abspath('.'), pdf)  #original file location
        newLoc = shutil.move(originalLoc, os.path.join(NewdirPath, pdf)) #move pdf to new folder
        print('Moving file "%s" moved to "%s"...' %(pdf, newLoc)) #say what's moving

os.listdir(NewdirPath) 

1 个答案:

答案 0 :(得分:0)

这里的正则表达式过大。 os模块提供了多种方法来帮助您提取有关文件的信息。 您可以在os模块中使用splitext方法来找到扩展名。

类似的事情应该起作用:

import os
import shutil

old_dir = 'C:\\Users\\Luke\\Documents\\coding\\python\\'

new_dir = 'Reading Material'
# You should always use underscore_notations to name variables instead of CamelCase (use for ClassNames) see https://www.python.org/dev/peps/pep-0008/

os.makedirs(new_dir, exist_ok=True)

for file_path in os.listdir(old_dir):
    if os.path.splitext(file_path)[1] == '.pdf':
        shutil.move(file_path, '{0}\\{1}'.format(new_dir, os.path.basename(file_path)))