Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to print and sort file alphabetically, but also skip the first line in the file

I’m quite new to coding, and for an assignment I’m trying to show simply the items in the file, sorted alphabetically, without the name, price, etc.

fname = input('Enter the file name: ')
try:
    fhand = open(fname)
except:
    print('File cannot be opened:', fname)
    exit()

print("")

data = fhand.readlines()
data.sort()
for i in range(len(data)):
    print(data[i])

When I run this code, it sorts the file the way I want it alphabetically, but the first line in the file is included in this sorting process.

Flash, 300, 1, Figurine, Dc

Hulk, 100, 1, Figurine, Marvel

Name, Price, Quantity, Product, Brand

Obi Wan Kenobi, 400.99, 1, Figurine, Star Wars

Spiderman, 30.50, 1, Comic, Marvel

Superman, 150, 1, Figurine, DC

Wolverine, 20, 2, Comic, Marvel

Ignore the context of the file content lol, just playing around with file sorting.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try to read all lines but store all except for the first line:

fname = input("Enter the file name: ")
try:
    fhand = open(fname)
except:
    print("File cannot be opened:", fname)
    exit()

print("")

# read all lines and store all lines except the first line:
data = fhand.readlines()[1:]

data.sort()
for i in range(len(data)):
    print(data[i])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading