Python - 删除多个文件
Python - Deleting multi files
我正在尝试删除多个文件。
我正在使用这个脚本,但出于某种原因它只删除了前 4 个而不删除其余的。如果我将它拆分为 2 个脚本,它就可以工作...我的问题是什么?
def fileDeleter():
try:
os.remove('apps.csv')
os.remove('columns.txt')
os.remove('columns_boot.txt')
os.remove('output.txt')
os.remove('routes.csv')
os.remove('route_apps.txt')
os.remove('route_domain.txt')
os.remove('route_hosts.txt')
os.remove('start.txt')
os.remove('space.txt')
except OSError:
pass
我的观点是静静地处理它们,如果文件令人兴奋则删除 - 如果没有通过。用户不需要看到文件不存在的错误。当我添加错误时,我得到的唯一错误是
WindowsError: [Error 2] The system cannot find the file specified: *filename*
这很好,因为我并不总是拥有所有文件。但是当我这样做时,脚本并没有删除所有这些。
你的主要问题似乎是你默默地处理异常,所以你对其他问题一无所知。您可能有更多问题,但这是最明显的问题。
一旦发现错误,程序就会继续。您需要做的是尝试一次删除每个文件并检查是否有错误。
fileList = ['apps.csv', 'columns.txt', 'columns_boot.txt', 'output.txt', 'routes.csv', 'route_apps.txt', 'route_domain.txt', 'route_hosts.txt', 'start.txt', 'space.txt']
for file in fileList:
try:
os.remove(file)
except OSError as e:
print("File '{}' could not be removed.".format(file))
# pass # => you really should do more than pass here...
这样,如果其中一个较早的文件出现错误,它就不会使程序短路。
我正在尝试删除多个文件。 我正在使用这个脚本,但出于某种原因它只删除了前 4 个而不删除其余的。如果我将它拆分为 2 个脚本,它就可以工作...我的问题是什么?
def fileDeleter():
try:
os.remove('apps.csv')
os.remove('columns.txt')
os.remove('columns_boot.txt')
os.remove('output.txt')
os.remove('routes.csv')
os.remove('route_apps.txt')
os.remove('route_domain.txt')
os.remove('route_hosts.txt')
os.remove('start.txt')
os.remove('space.txt')
except OSError:
pass
我的观点是静静地处理它们,如果文件令人兴奋则删除 - 如果没有通过。用户不需要看到文件不存在的错误。当我添加错误时,我得到的唯一错误是
WindowsError: [Error 2] The system cannot find the file specified: *filename*
这很好,因为我并不总是拥有所有文件。但是当我这样做时,脚本并没有删除所有这些。
你的主要问题似乎是你默默地处理异常,所以你对其他问题一无所知。您可能有更多问题,但这是最明显的问题。
一旦发现错误,程序就会继续。您需要做的是尝试一次删除每个文件并检查是否有错误。
fileList = ['apps.csv', 'columns.txt', 'columns_boot.txt', 'output.txt', 'routes.csv', 'route_apps.txt', 'route_domain.txt', 'route_hosts.txt', 'start.txt', 'space.txt']
for file in fileList:
try:
os.remove(file)
except OSError as e:
print("File '{}' could not be removed.".format(file))
# pass # => you really should do more than pass here...
这样,如果其中一个较早的文件出现错误,它就不会使程序短路。