2017-05-18 23 views
-2

我必須從一個文件中讀取數據並將其輸入到另一個按字母順序排列的文件中。所以我做了條,然後排序(),現在我不能因爲某種原因把它換成新的行可以請一些人指導我做什麼不正確。Python中的新行不起作用

 infile = open("unsorted_fruits.txt", "r") 
     outfile=open("sorted_fruits.txt","w") 



     for line in infile: 
      fruit=infile.read().split() 
      fruits = sorted(fruit) 
      timeflies = str(fruits) 
      outfile.write(timeflies + '\n'); 
      print (timeflies) 



     infile.close() 
     outfile.close() 
+1

... *它是如何工作不*? –

+0

你確定你的縮進是正確的嗎?看起來您正在爲輸入文件中的每一行執行所有步驟。 –

+0

無論如何...你的錯誤在這裏:'fruit = infile.read()。split()' –

回答

1

你做了什麼錯了:你已經在infile.read()第一次迭代過程中從infile讀到的一切,但對於第二次迭代,什麼都不剩閱讀。所以你應該在循環前讀取文件並遍歷排序列表。

試試這個:

infile = open("unsorted_fruits.txt", "r") 
outfile=open("sorted_fruits.txt","w") 

fruit=infile.read().split() 
fruits = sorted(fruit) 
for line in fruits: 
    timeflies = str(line) 
    outfile.write(timeflies) 
    print (timeflies) 
infile.close() 
outfile.close() 

注:.split()分裂在每一個空格,每個新線。所以如果你的水果名稱中有空格,分開。

你可以看看你的代碼的這個改進版:

with open("unsorted_fruits.txt", "r") as infile, 
     open("sorted_fruits.txt","w") as outfile: 
    fruits = sorted(infile.readlines()) 
    outfile.writelines(fruits) 
+0

這很好用,不太清楚我搞砸了還是我的意思是我看到了我搞砸了但不明白的地方它。非常感謝你btw。 – geekCoder

+1

你沒有完全向OP解釋他做錯了什麼... – jadsq

+1

@jadsq那裏,我解釋了:) – abccd

0

你在寫文章的陣列本身。這是一個可以工作的修改版本。

infile = open("unsorted_fruits.txt", "r") 
outfile=open("sorted_fruits.txt","w") 

fruit=infile.read().split() 

fruits = sorted(fruit) 
timeflies = str(fruits) 
print (timeflies) 

for fruit in fruits: 
    outfile.write(fruit + '\n') 

infile.close() 
outfile.close() 
+0

沒有數組參與... –

0

分析:

這裏是你的循環由線做什麼,行:

# 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