2015-04-29 65 views
0

我的父數據集每行包含1條推文。我正在清理推文並從推文中提取特徵詞並將其導出到csv。我可以導出除最後一行以外的所有內容。我使用的代碼follwoing片:無法將最後一行寫入csv

#Read the tweets one by one and process it 
fp = open('C:/Twitter_crawl/tweetDB4_import.csv', 'r') 


st = open('C:/Twitter_crawl/stopwords.txt', 'r') 
stopWords = getStopWordList('C:/Twitter_crawl/stopwords.txt') 

for line in fp.readlines(): 
    a = csv.writer(open('feature_vector.csv', 'a')) 
    processedTweet = processTweet(line) 
    featureVector = getFeatureVector(processedTweet) 
    a.writerow(featureVector) 
    print (featureVector) 
#end loop 
fp.close() 

任何人都可以請幫我與循環,使最後一排也被出口?

在此先感謝!

+0

不關閉文件可能會留下許多其他行不寫。最後一個只是容易注意的目標。 – jester112358

回答

0

您需要關閉文件feature_vector.csv。你實際上每次都通過循環打開它,這是不好的。在循環之前打開一次,然後關閉一次。

另外變量st不被使用。

0

正如在Paul Cornelius的回答中 - 您的問題是您每次繞着循環打開您的.csv文件,但沒有關閉它。

使用文件操作,使用with open('file', 'r') as openfile:構造更安全,因爲這會爲您重新關閉文件,即使發生異常並且腳本儘早終止。

事情是這樣的:

st = open('C:/Twitter_crawl/stopwords.txt', 'r') 
stopWords = getStopWordList('C:/Twitter_crawl/stopwords.txt') 

with open('C:/Twitter_crawl/tweetDB4_import.csv', 'r') as fp: 
    with open('feature_vector.csv', 'a') as op: 
     a = csv.writer(op) 
     for line in fp.readlines(): 
      processedTweet = processTweet(line) 
      featureVector = getFeatureVector(processedTweet) 
      a.writerow(featureVector) 
      print (featureVector) 
     #end loop 

我留在stopwords線,即使他們不使用....

0

看起來你不要關閉您的目標文件。 也許你應該使用類似的東西:

with open('feature_vector.csv', 'a') as csvfile: