A
A
Akshin Yolchuev2020-05-08 13:56:50
Python
Akshin Yolchuev, 2020-05-08 13:56:50

Why can't iterate through the files?

The problem is because of this fragment (Downloads\\)
I write and so Downloads\\ and so Downloads\ and so Downloads does not work, tell me how to do it

import os

a = r"C:\Users\AKSHIN\Downloads"

b = os.listdir(a)
for i in b:
  with open(r"C:\Users\AKSHIN\Downloads\\"+str(i),'r')as f:
    pass

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Karbivnichy, 2020-05-08
@hottabxp

Handle exceptions, it's not hard. I do not know if this script will work on Windows (of course, when changing paths), try this:

import os

os.chdir('/etc/') # Устанавливаем рабочую директорию
listFiles = os.listdir('./') # Получаем список объектов, относительно рабочей дериктории
for file in listFiles:
  try:
    with open(file,'r')as f:
      # Тут действия с файлом
      pass 
  except IsADirectoryError:
    print(file +'- это дериктория')
  except PermissionError:
    print(file + '- доступ запрещен')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question