2013-05-14 65 views
-1

我嘗試使用下面的代碼讀取Python中的CSV文件的文件:閱讀在python問題

with open(self.fileName, 'r') as openFile: 
      dataReading = openFile.read() 
     openFile.close() 
     splitData = dataReading.split("\n") 
     print splitDat 

一個 我不明白爲什麼我沒有得到任何輸出。

self.fileName是爲了表示計算機上的文件位置,我試圖打開它並在有新行的地方分割它。有人可以幫我解決這個問題嗎?

+6

有一件事,如果您使用'with',則在退出該塊後無需顯式關閉該文件。 – BlackVegetable 2013-05-14 14:16:04

+3

什麼是'read_data'?爲什麼在'with'爲你做這件事時關閉文件? – thegrinner 2013-05-14 14:16:06

+2

使用'csv'模塊讀取CSV文件。 – geoffspear 2013-05-14 14:18:53

回答

0

你是存儲在dataReading讀線,然後做read_data.split()

你可能打算這樣做:

def convert(self): 
     dataReading = [] 
     with open(self.fileName, 'r') as openFile: 
      dataReading = openFile.readlines() 
     for data in dataReading: 
      print data 
+0

對不起,這是複製它的一個錯誤,因爲我更改了變量名以便於閱讀。儘管如此,我仍然沒有輸出 – ReallyGoodPie 2013-05-14 14:18:46

+0

當您的代碼符合[Python代碼樣式指南](http://www.python.org/dev/peps/pep-0008/)時,「更易於閱讀」。 – Matthias 2013-05-14 14:24:48

0

不知道爲什麼你在新行字符分割,但代碼下面應該讀入你的文件並逐行打印(在新行字符分割後)。

with open(self.fileName, 'r') as openFile: 
    for line in openFile: 
     l_split = line.split('\n') 
     print l_split