分析:
這裏是你的循環由線做什麼,行:
# Reading each line of input:
for line in infile:
# Ignore that first line and read
# the rest of the file.
# Split that into individual fruit names
fruit=infile.read().split()
# Sort the list of fruits #2 through end-of-file
fruits = sorted(fruit)
# Make a string representation of that list.
timeflies = str(fruits)
# Put a single line feed after that string and dump it
# to the output file.
outfile.write(timeflies + '\n');
print (timeflies)
只是爲了明確這一點,timeflies
是一個字符串,看起來像這樣:
"['apple', 'kumquat', 'persimmon', 'pineapple', 'tomato']"
這不是一個列表;這是一個字符串,看起來像你可能想要使用的列表。也許是有用的下一步將是
timeflies = '\n'.join(fruits)
但是,你仍然浪費了你的循環(它只能執行一次),失去了第一道防線。你看到那(失敗)是如何工作的?
SOLUTION:
infile = open("unsorted_fruits.txt", "r")
outfile=open("sorted_fruits.txt","w")
# Make a list of the input fruits
fruit_list = []
for line in infile:
fruit_list.extend(line.split())
# Sort that list
fruit_list.sort()
# Print it to the output file, one line at a time
for fruit in fruit_list:
print(fruit, file=outfile)
輸入文件:
banana
pineapple
tomato
kumquat
apple
persimmon
輸出文件:
$ cat sorted_fruits.txt
apple
banana
kumquat
persimmon
pineapple
tomato
... *它是如何工作不*? –
你確定你的縮進是正確的嗎?看起來您正在爲輸入文件中的每一行執行所有步驟。 –
無論如何...你的錯誤在這裏:'fruit = infile.read()。split()' –