简体   繁体   中英

Python script is not listing a file in the directory?

I have a slight question.

I have the following function:

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

and in the directory ( Defined by com_dir ) there are three files.

a.gcom b.gcom c.gcom

when running getCommands()

The following is outputted:

ab

Files a and b are shown ,however, c is not shown, All files are in the directory and all are using the same file extension: .gcom which is also com_ext variable wise.

Does anyone have any hints as to why file c is not being shown?

Side note: There seems to be a blank space in the output where c should be however Im not sure if this has any part in the issue at hand and isn't just simply a accidental space placed elsewhere in the script.

strip removes all the given characters from both ends of your string, whatever order they occur in. If your string is c.gcom , then strip('.gcom') removes all the characters . , g , c , o and m from the ends of your string, leaving nothing left. It doesn't stop stripping until it hits a character that is not . , g , c , o or m (or removes everything).

If you have a string ending in .gcom , and you just want to remove that ending, you can use:

z = file[:-5]

or, using your com_ext variable

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

Python 3 does it much better than 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))

But if you REALLY have to use 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]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM