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

Time:06-03

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.

CodePudding user response:

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])
  • Related