0
votes

I am getting syntax error in my code. Can anyone say whats wrong in the syntax?

Traceback (innermost last):
  (no code object) at line 0
  File "<string>", line 867
            if (file.endsWith(".ear") || file.endsWith(".war")):
                                               ^
SyntaxError: invalid syntax

My code:

for file in [ears for ears in os.listdir(warPath)]:
  if (file.endsWith(".ear") || file.endsWith(".war")):
    file_list.append(file)

I have a warpath where there are multiple war ,ear and sql files. my below condition should read all the files and if condition should filter only war and ear files and store it in a file_list.

1

1 Answers

2
votes

You are using || where you meant to use or:

if file.endswith(".ear") or file.endswith(".war"):

Note that the str.endswidth() method name is all lowercase.

Jython supports at least Python 2.5, so you can just use a tuple:

if file.endswith((".ear", ".war")):

See the Jython string methods documentation:

str.endswith(suffix[, start[, end]])

Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.

Changed in version 2.5: Accept tuples as suffix.

Your for loop looks overly complicated; no need to loop over os.listdir() in a list comprehension:

for file in os.listdir(warPath):
    if file.endswith((".ear", ".war")):
        file_list.append(file)

but if you can use a list comprehension there then you probably are using a Jython 2.7 beta, so you may as well make the file_list definition a list comprehension:

file_list = [f for f ir os.listdir(warPath) if file.endswidth(('.ear', '.war'))]

If you are using an older Jython version (such as 2.1, as bundled with Websphere 8), you cannot use either a tuple argument to str.endswith() nor list comprehensions. You'll have to append still:

for fname in os.listdir(warPath):
    if fname.endswith(".ear") or fname.endswith(".war"):
        file_list.append(fname)

I've used fname here instead of file, which is a built-in name in Python. Best not mask it.