如何删除python try/except块中的重复异常错误?
我是一名新的python程序员,一直在制作一个文件排序函数,以获取一个文件名,并将其整齐地排列在一个文件结构中,即年/月/日。下面的代码可以工作,但是看起来很难看,并且有很多重复的异常错误,我想删除这些错误。 希望看到如何提高这段代码的效率,因为它将经常运行。提前谢谢如何删除python try/except块中的重复异常错误?,python,Python,我是一名新的python程序员,一直在制作一个文件排序函数,以获取一个文件名,并将其整齐地排列在一个文件结构中,即年/月/日。下面的代码可以工作,但是看起来很难看,并且有很多重复的异常错误,我想删除这些错误。 希望看到如何提高这段代码的效率,因为它将经常运行。提前谢谢 def fileSort(day, month, year, file): global filewritten try: os.makedirs(togoto + '/' + year) except
def fileSort(day, month, year, file):
global filewritten
try: os.makedirs(togoto + '/' + year)
except FileExistsError:
pass
try: os.makedirs(togoto + '/' + year + '/' + month)
except FileExistsError:
pass
try:
os.makedirs(togoto + '/' + year + '/' + month + '/' + day)
except FileExistsError:
pass
try:
shutil.move(path + '/' + file,
togoto + '/' + year + '/' + month + '/' + day + '/' + file)
filewritten += 1
except FileExistsError:
pass
您可以定义自己的函数来缩短代码,这也有利于可重用性:
def create_dir(name):
try:
os.makedirs(name)
except FileExistsError:
pass
def fileSort(day, month, year, file):
global filewritten
create_dir(togoto + '/' + year)
create_dir(togoto + '/' + year + '/' + month)
create_dir(togoto + '/' + year + '/' + month + '/' + day)
try:
shutil.move(path + '/' + file, togoto + '/' + year + '/' + month + '/' + day + '/' + file)
filewritten += 1
except FileExistsError:
pass
os.makedirs()
,所以应该足够了
try:
os.makedirs(togoto + '/' + year + '/' + month + '/' + day)
except FileExistsError:
pass
try:
shutil.move(path + '/' + file,
togoto + '/' + year + '/' + month + '/' + day + '/' + file)
filewritten += 1
except FileExistsError:
pass
这是对原始版本的一点改进
顺便说一句,os.path.join()是您的朋友:
source = os.path.join(path, file)
targetdir = os.path.join(togoto, year, month, day)
target = os.path.join(togoto, year, month, day, file)
try:
os.makedirs(targetdir)
except FileExistsError:
pass
try:
shutil.move(source, target)
filewritten += 1
except FileExistsError:
pass
如果您的Python足够新,最好使用os.makedirs()
的所有功能:
source = os.path.join(path, file)
targetdir = os.path.join(togoto, year, month, day)
target = os.path.join(targetdir, file)
os.makedirs(targetdir, exist_ok=True) # i. e. no exception on an already existing path.
try:
shutil.move(source, target)
filewritten += 1
except FileExistsError:
pass
首先:仅对最里面的目录使用makedirs
:
try:
os.makedirs(togoto + '/' + year + '/' + month + '/' + day)
except FileExistsError:
pass
然后请注意,您可能应该使用os.path.join
来形成路径,因此:
try:
os.makedirs(os.path.join(togoto, year, month, day))
except FileExistsError:
pass
而且。。。在Python3(3.2+)中,有一个参数exists\u ok
,可以设置为True
,这样,如果叶子目录存在,就不会引发异常,因此我们得到
os.makedirs(os.path.join(togoto, year, month, day), exists_ok=True)
最后请注意,如果目标存在,shutil.move
可能会或可能不会抛出一个fileexisterror
。您可以使用os.path.isdir
从第一次检查的最长路径开始并向后移动,查看每个目录是否存在。如果目录已经存在,它会减少你的工作量。这个答案可能会有助于啊,哇,这太整洁了。非常感谢,非常感谢!