4

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!

2
  • oh, sorry, below cd = input("change directory to: ") it should read: Commented May 19, 2016 at 12:03
  • that middel line is actuely part of the code... sorry, stack overflow missunderstood it Commented May 19, 2016 at 12:05

1 Answer 1

5

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))]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.