Skip to content
Advertisement

putting file names in an array using os in python

I want to create a program that will use os to make an ls of a directory and then put the files in a array. However, ls does not list the names one by one, so I am kind of stuck, because there’s nothing constant by which I can tell when the next name starts.

Here is the actual code:

import os
cd = input("Change directory to:   ")

while cd != "x":
    os.chdir(cd)
    command = os.popen('ls')
    ls = command.read()
    print(ls)
    cd = input("Change directory to:   ")
    count = 0
    word = ""

for character in ls:
    while count == 0 :
        if character!= " ":
            count = 1
            word += character

        elif character == " ":
            print(word)

So the idea is that, when the program starts, it should ask you which directory you want to change to and then run ls on that directory. Then if you type back x, it should just print the first directory to the screen. However, as I said, it just prints the entire list.

Can anybody help me with this?

Any help appreciated. Thanks!

Advertisement

Answer

You can use the already-ready-to-go os.listdir – it will get you everything that’s in a directory – files and directories.

But if you want just the files, you could add the usage of os.path:

from os import listdir
from os.path import isfile, join
files = [file for file in listdir(path) if isfile(join(path, file))]
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement