How to optimize this script

Posted by marks34 on Stack Overflow See other posts from Stack Overflow or by marks34
Published on 2011-01-08T12:43:11Z Indexed on 2011/01/08 12:53 UTC
Read the original article Hit count: 158

Filed under:
|

I have written the following script. It opens a file, reads each line from it splitting by new line character and deleting first character in line. If line exists it's being added to array. Next each element of array is splitted by whitespace, sorted alphabetically and joined again. Every line is printed because script is fired from console and writes everything to file using standard output. I'd like to optimize this code to be more pythonic. Any ideas ?

import sys

def main():
    filename = sys.argv[1]
    file = open(filename)
    arr = []
    for line in file:
        line = line[1:].replace("\n", "")
        if line:
            arr.append(line)

    for line in arr:
        lines = line.split(" ")
        lines.sort(key=str.lower)
        line = ''.join(lines)
        print line

if __name__ == '__main__':
    main()

© Stack Overflow or respective owner

Related posts about python

Related posts about optimization