我對編碼很陌生,對于一項任務,我試圖簡單地顯示檔案中的專案,按字母順序排序,沒有名稱、價格等。
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])
當我運行此代碼時,它會按照我想要的字母順序對檔案進行排序,但檔案中的第一行包含在此排序程序中。
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
忽略檔案內容的背景關系大聲笑,只是在玩檔案排序。
uj5u.com熱心網友回復:
嘗試讀取所有行,但存盤除第一行之外的所有行:
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])
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/485505.html
標籤:python-3.x CSV
