- 1 year ago
Python Pathlib glob fails on long pathnames on windows - how to ignore the error?
When using pathlib
and the glob
function on Windows, you may encounter errors related to long pathnames exceeding the maximum limit allowed by the operating system. To work around this issue and ignore the error, you can use a try-except block to catch the exception raised by glob
and handle it gracefully.
Here's an example:
pythonimport pathlib
try:
# Attempt to use glob
files = list(pathlib.Path('your_directory').glob('**/*.txt'))
except OSError as e:
# Handle the error
print(f"Error occurred: {e}")
files = []
# Process the files as needed
for file in files:
print(file)
In the above code, we wrap the glob
function call with a try-except block. If an OSError
is raised due to the long pathnames, the code within the except block will be executed. In this example, we simply print the error message and assign an empty list to the files
variable.
By catching and handling the exception, you can prevent the error from halting your program and continue execution with an empty list or any alternative approach you prefer.
Note that this solution ignores the error and continues the program execution. If you need to process the files with long pathnames, you may need to consider alternative methods or libraries specifically designed to handle long paths on Windows, such as pywin32
.