FileNotFoundError用于快捷方式文件

时间:2017-12-06 15:54:58

标签: python file shortcut

我正在尝试练习项目,删除不需要的文件(章节:组织文件,页面:213)从书中使用python自动执行枯燥的任务。完整的问题陈述是,

一些不需要但非常大的文件或文件夹占用硬盘驱动器上的大部分空间并不罕见。如果你想在计算机上腾出空间,你可以通过删除最大量的不需要的文件来获得最大的收益。但首先你必须找到它们。

编写一个遍历文件夹树并搜索例外的程序 理想的大文件或文件夹 - 比如文件大小超过的文件或文件夹 100MB。 (请记住,要获取文件的大小,可以使用os.path.getsize() os模块。)打印这些文件及其绝对路径到屏幕。

这是我的代码,

#!/usr/bin/python
# A program to walk a path and print all the files name with size above 100MB

import os

pathInput = os.path.abspath(input('Enter the path for the directory to search '))

for folder, subFolders, files in os.walk(pathInput):
    for file in files:
        file = os.path.join(folder, file)
        if int(os.path.getsize(file)) > 100000000:
            print('File located, Name: {fileName}, Location: {path}'.format(fileName=file, path=folder))

但是对于某些文件,我得到FileNotFoundError。所以,在尝试这个时

#!/usr/bin/python
# A program to walk a path and print all the files name with size above 100MB

import os

pathInput = os.path.abspath(input('Enter the path for the directory to search '))

for folder, subFolders, files in os.walk(pathInput):
    for file in files:
        file = os.path.join(folder, file)
        try:
            if int(os.path.getsize(file)) > 100000000:
                print('File {fileName} located at {path}'.format(fileName=file, path=folder))
        except FileNotFoundError:
            print('FileNotFoundError: {}'.format(file))

我发现大小为零字节的快捷方式文件会导致错误。

那么,我该如何克服这个错误呢? python中是否有任何函数检查文件是否是快捷方式?

1 个答案:

答案 0 :(得分:1)

您可以使用os.path.islink()

import os

pathInput = os.path.abspath(input('Enter the path for the directory to search '))

for folder, subFolders, files in os.walk(pathInput):
    for file in files:
        if not os.path.islink(file):
           # rest of code
相关问题