2017-02-11 107 views
0
import csv 
with open("HORSES.csv") as f: 
for row in csv.reader(f): 
    # Number of pages plus one 
    for horse in row: 
     print (horse) 
with open("%s.txt" % horse, "w") as f: 
      f.close() 

這個內容文件horses.csvwest,usa,asia,black。輸出os正常,但創建.txt文件只black.txt文件的結尾horses.csv不創建文件txt從列表pd csv文件,如何創建.txt文件與列表文件中的文件名horses.csv像這樣west.txt usa.txt asia.txt black.txt如何用python 2.7創建文件txt文件csv 2.7

回答

0

您最後的with聲明不是循環的一部分,因此您只能獲取存儲在horse中的最後一個值。

如果需要多個.txt文件,把它們放在一個循環,並創建它們一次一個:

import csv 

Horse_types = [] 

with open("HORSES.csv") as f: 
    for row in csv.reader(f): 
     for horse in row: 
      print (horse) 
      Horse_types.append(horse) 

for ht in Horse_types: 
    with open("%s.txt" % ht, "w") as f: 
     # More stuff here? 
     f.close() 
+0

感謝,你可以幫我再次充滿我的代碼?以上代碼與beatifulsoup腳本的一部分,因爲iam總是出錯 –