1

I want to loop through files in a directory (I get that working easily) but skip files in subdirectories (I don't get this working).

How would I achieve this? Currently I use this:

for subdir, dirs, files in os.walk(scriptdir1):
    for file in files:
        if os.path.isfile(scriptdir + file):
            with open(file, "rb") as f:
                dbx.files_upload(f.read(), "/" + file, mode=dropbox.files.WriteMode.overwrite)

This is what my folder looks like (This could change so I don't want any folder specific answers):

enter image description here

So I want to loop through the files in this directory, and skip the files that are in subdirectories. I only want the files that are in THIS directory.

Thanks

WoJo
  • 500
  • 1
  • 3
  • 20
  • 2
    Why are you doing `os.path.isfile`??? `os.walk` will return *only* files in its third output. If you don't want to go in subdirectories why are you using `os.walk`? Use `os.listdir`+`os.path.isfile`. – Bakuriu Feb 03 '20 at 17:18
  • 2
    Does this answer your question? [List files ONLY in the current directory](https://stackoverflow.com/questions/11968976/list-files-only-in-the-current-directory) – Greg Feb 03 '20 at 17:18
  • Thanks @Greg, I don't know why I couldn't find this. I actually searched for an hour.. Also thank you Bakuriu, I will comment this as answer. – WoJo Feb 03 '20 at 17:23

2 Answers2

2

I used this to let it work:

files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
    with open(f, "rb") as fi:
        dbx.files_upload(fi.read(), "/" + f, mode=dropbox.files.WriteMode.overwrite)
        print("Uploaded: " + f)

Thanks to Greg and Bakuriu for pointing out the right answer

WoJo
  • 500
  • 1
  • 3
  • 20
0

You can use glob here:-

import glob
file = glob.glob(scriptdir1 + "/*/*")
 with open(file, "rb") as f: dbx.files_upload(f.read(), "/"+file,mode=dropbox.files.WriteMode.overwrite)

You can also write regex in place to of * to match some particular files.

B25Dec
  • 2,301
  • 5
  • 31
  • 54