2016-12-06 139 views
-2

我想要從一個文件夾中的多個.txt文件中讀取數據,並將每行讀取爲一個列表。在一個文件夾中讀取多個.txt文件

example name of the files

example content of each file

這是我的代碼,但不打印輸出。

import glob 
import errno 
path = '/Users/xccxken/PycharmProjects/untitled7/NNRelease/*.txt' 
files = glob.glob(path) 
for name in files: 
    try: 
     with open(name) as f: 
      for line in f: 
       words = list() 
       for word in line.split(): 
        words.append(word) 
    except IOError as exc: 
     if exc.errno != errno.EISDIR: 
      raise 
    print(words) 

我希望由此而來是兩個列表A和B

a=[class,company,family,..] 
b=[size, size, size,...] 

另一個問題是打印列表中包含了一些空的列表,(我認爲這是因爲原來的txt文件有一個空行)請告訴我如何刪除這些空列表。謝謝!

此外,我需要刪除含有「#」感謝名單!

回答

1

我認爲files可能是空的。使用絕對路徑,或者os.chdir進入目錄

import glob 
import errno 
path = 'C:/Users/xccxken/PycharmProjects/untitled7/NNRelease/*.txt' #note C: 
files = glob.glob(path) 
for name in files: 
    try: 
     with open(name) as f: 
      for line in f: 
       print(line.split()) 
    except IOError as exc: #Not sure what error this is 
     if exc.errno != errno.EISDIR: 
      raise 

要只用數據打印行

with open(name) as f: 
     for line in f: 
      split = line.split() 
      if split: 
       print(line.split()) 
+0

謝謝!它的工作原理! –

+0

另一個問題是打印列表包含一些空的列表,(我認爲它是b因爲原來的txt文件有空行)你能告訴我如何刪除這些空列表?非常感謝您的寶貴時間! –

+0

@lyuketing查看我的編輯 –