【问题标题】:Python script is not listing a file in the directory?Python脚本没有在目录中列出文件?
【发布时间】:2018-05-11 13:27:58
【问题描述】:

我有一个小问题。

我有以下功能:

def getCommands():
    for file in os.listdir(com_dir):
        if file.endswith(com_ext):
            z = string.strip(file, '.gcom')
            print z

在目录(由com_dir定义)中有三个文件。

a.gcom b.gcom c.gcom

运行时getCommands()

输出如下:

a b

显示了文件 a 和 b,但是没有显示 c,所有文件都在目录中,并且都使用相同的文件扩展名:.gcom,这也是 com_ext 变量明智的。

有人知道为什么文件 c 没有显示吗?

旁注:输出中似乎有一个空格 c 应该是但是我不确定这是否与手头的问题有关,而不仅仅是脚本中其他地方的意外空间.

【问题讨论】:

  • 为什么代码一次说“com_ext”,一次说“'.gcom'”?
  • print os.listdir(com_dir)确切输出是什么? com_ext == 'gcom' or com_ext == '.gcom' 是真的吗?
  • @FHTMitchell 确切的输出是三个文件,a.gcomb.gcomc.gcom
  • 不,不是。这是['a.gcom', 'b.gcom', 'c.gcom']。这么简单的指令……无论如何,问题已经回答了。

标签: python python-2.7


【解决方案1】:

strip 删除字符串两端的所有给定字符,无论它们出现的顺序如何。如果你的字符串是c.gcom,那么strip('.gcom') 删除所有字符.g、@987654326 @、om 从字符串的末端开始,什么都不剩。它不会停止剥离,直到遇到不是.gcom 的字符(或删除所有内容)。

如果您有一个以.gcom 结尾的字符串,并且您只想删除该结尾,您可以使用:

z = file[:-5]

或者,使用您的 com_ext 变量

com_ext = '.gcom'
...
if file.endswith(com_ext):
    z = file[:-len(com_ext)]

【讨论】:

  • 它会从两端删除字符,对吧?
  • @plalanne 会的,但这不是重点。即使 OP 使用了rstrip(从右边剥离),它也会产生相同的效果,因为整个字符串都是由可剥离字符组成的。
  • 谢谢!这解决了我的问题@khelwood
【解决方案2】:

Python 3 比 Python 2 做得更好:

from pathlib import Path

def getCommands(com_dir, com_ext):  # com_ext = "gcom"
    for f in Path(com_dir).glob("*." + com_ext):
        print ("{}".format(f.stem))

但如果你真的必须使用 Python 2:

def getCommands(com_dir, com_ext):
    for file in os.listdir(com_dir):
        s = f.split('.' + com_ext)
        if len(s) > 1:
            print("{}".format(s[0]))

【讨论】:

    猜你喜欢
    • 2013-11-14
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    • 2011-07-11
    相关资源
    最近更新 更多