0
directory = r'/home/bugramatik/Desktop/Folder'

for filename in os.listdir(directory):
    file = open('/home/bugramatik/Desktop/Folder'+filename,'r')
    print(BinaryToString(file.read().replace(" ","")))

I want to read all files inside of the a folder same order with folder structure.

For example my folder is like a b c d

But when I run the program at above it shows like c a d b

How can I read it like a,b,c,d?

1 Answers1

1

The order in os.listdir() is actually more correct. But if you want to open the files in alphabetical order, like ls displays them, just reimplement the sorting it does.

for filename in sorted(os.listdir(directory)):
    with open(os.path.join(directory, filename) ,'r') as file:
        print(BinaryToString(file.read().replace(" ","")))

Notice the addition of sorted() and also the use of os.path.join() to produce an actually correct OS-independent file name for open(), and the use of a with context manager to fix the bug where you forgot to close the files you opened. (You can leave a few open just fine, but the program will crash with an exception when you have more files because the OS limits how many open files you can have.)

tripleee
  • 175,061
  • 34
  • 275
  • 318