I have a question about the listdir function of python's os module.

Asked 1 years ago, Updated 1 years ago, 241 views

Hello, I was working on an example using the pythonos module.

I have a question.

#Set file path
file_der1 = 'C:/Users/maker01/Downloads/a'
file_der2 = 'C:/Users/maker01/Downloads/b'
file_der3 = 'C:/Users/maker01/Downloads/c'
#Saves the list of files per folder to the list variable
file_list1 = os.listdir(file_der1)
file_list2 = os.listdir(file_der2)
file_list3 = os.listdir(file_der3)

contained in a folder called a, b, and c in a specific location as above

To scratch the list of files into a list variable, click the listdir on the os module.

When I used it, but there was no corresponding path, there was an error in the line and the movement itself stopped.

Can I know how to ignore the error and proceed with the code even if there is an error related to the content?

python

2023-01-26 14:10

2 Answers

First, you need to make sure that the path exists.:

import os

file_der1 = 'C:/Users/maker01/Downloads/a'

if os.path.exists(file_der1):
    file_list1 = os.listdir(file_der1)
else:
    print ("I don't have one")

공식 도움말: https://docs.python.org/3/library/os.path.html#os.path.exists

Search Keywords:


2023-01-26 14:16

First, it is necessary to check if the file is located there.

In this case, we recommend using the os.path.isfile function.

Do import os.path, check the path with os.path.isfile(file_der1~3), and put it in the list variable, right?

Oh, and Python will display a file path error if it is not a directory that has already been created. Please be careful and check if the directory has been created in advance, and if there is none, it seems better to add the directory creation of the directory.

I hope it helped you. Please press it!

Below is an example to help you understand.~

import os.path

#Set file path
file_der1 = 'C:/Users/maker01/Downloads/a'
file_der2 = 'C:/Users/maker01/Downloads/b'
file_der3 = 'C:/Users/maker01/Downloads/c'
#Saves the list of files per folder to the list variable
if os.path.isfile(file_der1):
  file_list1 = os.listdir(file_der1)
elif os.path.isdir(file_der2):
  file_list2 = os.listdir(file_der2)
elif os.path.exists(file_der3):
  file_list3 = os.listdir(file_der3)


2023-01-26 14:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.