Reputation: 959
I'm trying the practice project, Deleting Unneeded files (Chapter: Organising files, Page: 213) from the book Automate the boring task with python. The full problem statement is,
It’s not uncommon for a few unneeded but humongous files or folders to take up the bulk of the space on your hard drive. If you’re trying to free up room on your computer, you’ll get the most bang for your buck by deleting the most massive of the unwanted files. But first you have to find them.
Write a program that walks through a folder tree and searches for excep- tionally large files or folders—say, ones that have a file size of more than 100MB. (Remember, to get a file’s size, you can use os.path.getsize() from the os module.) Print these files with their absolute path to the screen.
Here's my code,
#!/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))
However for some files I get FileNotFoundError
. So, when trying this
#!/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))
I found that the files which are shortcuts with size zero bytes causes the error.
So, how should I overcome this error? Is there any function in python is check if the file is shortcut?
Upvotes: 1
Views: 471
Reputation: 198
You can use 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
Upvotes: 1