这是一个搜索大于指定大小的文件的脚本:
def size_scan(folder, size=100000000):
"""Scan folder for files bigger than specified size
folder: abspath
size: size in bytes
"""
flag = False
for folder, subfolders, files in os.walk(folder):
# skip 'anaconda3' folder
if 'anaconda3' in folder:
continue
for file in files:
file_path = os.path.join(folder, file)
if os.path.getsize(file_path) > size:
print(file_path, ':', os.path.getsize(file_path))
flag = True
if not flag:
print('There is nothing, Cleric')
在Linux中扫描根文件夹时出现以下错误消息:
Traceback (most recent call last):
File "<ipython-input-123-d2865b8a190c>", line 1, in <module>
runfile('/home/ozramsay/Code/sizescan.py', wdir='/home/ozramsay/Code')
File "/home/ozramsay/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 880, in runfile
execfile(filename, namespace)
File "/home/ozramsay/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/home/ozramsay/Code/sizescan.py", line 32, in <module>
size_scan('/')
File "/home/ozramsay/Code/sizescan.py", line 25, in size_scan
if os.path.getsize(file_path) > size:
File "/home/ozramsay/anaconda3/lib/python3.6/genericpath.py", line 50, in getsize
return os.stat(filename).st_size
FileNotFoundError: [Errno 2] No such file or directory: '/run/udev/link.dvdrw'
我猜这是因为Python解释器无法扫描自己,所以我试图从搜索中跳过'anaconda3'文件夹(在上面的代码中用#skip anaconda文件夹标记)。但是,错误消息保持不变。
有人可以解释一下吗?
(如果此处不允许此类问题,请告诉我,并且应该进行编辑。谢谢)
答案 0 :(得分:1)
文件python正在尝试获取os.stat(filename).st_size
的大小是一个断开的链接。断开的链接是已删除目标的链接。它就像一个互联网链接,提供404.要在脚本中修复此问题,请检查它是否是文件(首选),或使用try / catch(不是首选)。要检查文件是文件而不是链接损坏,请使用os.path.isfile(file_path)
。您的代码应如下所示:
def size_scan(folder, size=100000000):
"""Scan folder for files bigger than specified size
folder: abspath
size: size in bytes
"""
flag = False
for folder, subfolders, files in os.walk(folder):
# skip 'anaconda3' folder
if 'anaconda3' in folder:
continue
for file in files:
file_path = os.path.join(folder, file)
if os.path.isfile(file_path) and (os.path.getsize(file_path) > size):
print(file_path, ':', os.path.getsize(file_path))
flag = True
if not flag:
print('There is nothing, Cleric')
因此,在获得大小之前,它会检查文件是否确实存在,并检查所有链接以确保它存在。 Related SO post