在python中使用os将文件名放入数组中

Cid*_*-El 3 python operating-system python-3.x

我想创建一个将使用一个程序os来做出ls一个目录,然后把文件阵列英寸 然而,ls没有一一列出名字,所以我有点卡住了,因为没有什么恒定的可以告诉我下一个名字是什么时候开始的。

这是实际的代码:

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)
Run Code Online (Sandbox Code Playgroud)

所以这个想法是,当程序启动时,它应该询问您要更改到哪个目录,然后ls在该目录上运行。然后,如果您输入 back x,它应该只将第一个目录打印到屏幕上。但是,正如我所说,它只是打印整个列表。

有人可以帮我解决这个问题吗?

任何帮助表示赞赏。谢谢!

Ido*_*dos 5

您可以使用已经准备好的os.listdir- 它会为您提供目录中的所有内容 - 文件和目录。

但是如果你只想要文件,你可以添加以下用法os.path

from os import listdir
from os.path import isfile, join
files = [file for file in listdir(path) if isfile(join(path, file))]
Run Code Online (Sandbox Code Playgroud)