Python - 如果文件夹不存在如何跳过该过程
Python - How to skip the process if folder does not exist
我正在尝试编写一个 Python 脚本来检查文件夹中是否存在文件,如果是,则打印可用文件,否则跳过这些步骤并检查下一个文件夹。我执行的另一个附加步骤是,如果文件夹中有任何子文件夹,我会删除该子文件夹。但是,如果该文件夹不存在,代码将失败。如果没有,我怎么能跳过该文件夹 exist.Given 下面是我使用的代码:
import pandas as pd
import glob
import numpy as np
import os
import os, shutil
path = r'/Users/scott/desktop/sales_data/store1/2018-05-10'
for the_file in os.listdir(path):
file_path = os.path.join(path, the_file)
try:
if os.path.isdir(file_path): shutil.rmtree(file_path)
except Exception as e:
print(e)
我得到的错误是
FileNotFoundError: [Errno 2] No such file or directory: '/Users/scott/desktop/sales_data/store1/2018-05-10'
任何人都可以提供帮助。谢谢
这就是我所做的..将在您的 for 循环之上。
您的 for 循环实际上是在检查路径,但您不检查它查找的路径是否存在。
path = r'/Users/scott/desktop/sales_data/store1/2018-05-10'
if not os.path.isdir(path):
<do your error code here>
for the_file in os.listdir(path):
file_path = os.path.join(path, the_file)
try:
if os.path.isdir(file_path): shutil.rmtree(file_path)
except Exception as e:
print(e)
我正在尝试编写一个 Python 脚本来检查文件夹中是否存在文件,如果是,则打印可用文件,否则跳过这些步骤并检查下一个文件夹。我执行的另一个附加步骤是,如果文件夹中有任何子文件夹,我会删除该子文件夹。但是,如果该文件夹不存在,代码将失败。如果没有,我怎么能跳过该文件夹 exist.Given 下面是我使用的代码:
import pandas as pd
import glob
import numpy as np
import os
import os, shutil
path = r'/Users/scott/desktop/sales_data/store1/2018-05-10'
for the_file in os.listdir(path):
file_path = os.path.join(path, the_file)
try:
if os.path.isdir(file_path): shutil.rmtree(file_path)
except Exception as e:
print(e)
我得到的错误是
FileNotFoundError: [Errno 2] No such file or directory: '/Users/scott/desktop/sales_data/store1/2018-05-10'
任何人都可以提供帮助。谢谢
这就是我所做的..将在您的 for 循环之上。
您的 for 循环实际上是在检查路径,但您不检查它查找的路径是否存在。
path = r'/Users/scott/desktop/sales_data/store1/2018-05-10'
if not os.path.isdir(path):
<do your error code here>
for the_file in os.listdir(path):
file_path = os.path.join(path, the_file)
try:
if os.path.isdir(file_path): shutil.rmtree(file_path)
except Exception as e:
print(e)