Skip to content Skip to sidebar Skip to footer

File Sorting In Python

I would like to sort a file in Python based on numerical values: My input file looks like this: 66135 - A 65117 - B 63301 - C 63793 - D Output should be: 63301 - C 63793 - D 65117

Solution 1:

f2.writelines(sorted(f1, key=lambda line:int(line.split()[0])))

where f2 is your output file and f1 is your input file.

Solution 2:

you can try this way

withopen('filename','r') as file:
    # spilt() the line with '-'
    lis=[line.strip().split('-') for line in file]
    # sort the lis using the valuesprintsorted(lis,key=lambda x:int(x[0].strip()))

Solution 3:

Here is a complete code for that.

withopen('inputFileName') as fp:
    lst = map(lambda s:s.rstrip(), fp.readlines())

withopen('outputFileName', 'w') as fp:
    fp.write("\n".join(sorted(lst, key=lambda s:int(s.split()[0]))))

Post a Comment for "File Sorting In Python"