2016-07-27 136 views
0

我想將空格分隔的.txt文件的內容複製到與列對應的單獨列表中,但我找不到解決此問題的方法。將空格分隔的字符串列複製到列表

.txt文件的樣品是這樣的:

Product 6153990c-14fa-47d2-81cf-a253f9294f96 - Date: 2016-06-29T09:47:27Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 3.08 GB 

Product cac95c2a-2d6e-477a-848f-caccbd219d39 - Date: 2016-06-29T09:47:27Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 6.32 GB 

Product c65147d3-ee3c-4f33-9e09-ea234d3543f7 - Date: 2016-06-29T09:40:32Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 4.00 GB 

Product fd1860e3-5d57-429e-b0c7-628a07b4bd5c - Date: 2016-06-27T09:03:49Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 6.25 GB 

Product ba8e4be4-502a-4986-94ce-d0f4dec23b5c - Date: 2016-06-27T09:03:49Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 5.52 GB 

Product b95cb837-6606-484b-89d6-b10bfaead9bd - Date: 2016-06-26T09:30:35Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 5.81 GB 

Product 96b64cfe-fc2e-4808-8356-2760d9671839 - Date: 2016-06-26T09:30:35Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 6.14 GB 

Product 20bb3c9e-bd15-417a-8713-3ece6090dd95 - Date: 2016-06-24T08:51:49Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 4.89 GB 

Product 5bf78d9b-a12b-4e54-aba7-299ae4ac0756 - Date: 2016-06-24T08:51:49Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 5.93 GB 

如果我使用空間分隔符分割的文件,列將是(逗號被包括在一些列):

Product 
59337094-226a-4d64-94b1-3fee5f5cbfe2 
- 
Date: 
2016-07-26T09:30:38Z, 
Instrument: 
MSI, 
Mode: 
, 
Satellite: 
Sentinel-2, 
Size: 
5.07 
GB 

我試圖做的(例如第一列):

list = [] 
with open('D:\GIS\Sentinel\cmd_output.txt', 'r') as file: 
    reader = csv.reader (file, delimiter = ' ') 
    for a,b,c,d,e,f,g,h,i,j,k,l,m,n in reader: 
     list.append(a) 
print list 

但它不工作,併發送錯誤:

ValueError: need more than 1 value to unpack

如何爲文件中的每個列執行此操作? 謝謝!

+1

如果您確定您使用了正確的分隔符,那麼您會將您的拆包零件包裝在「try-except」中,以便處理有缺陷的行。 – Kasramvd

+0

我不知道該怎麼做。我不是Python的高級用戶。 – Litwos

+0

你能展示實際的追溯?你爲什麼只是追加一個?它看起來像'產品'的價值? –

回答

1

reader變量沒有你覺得形似,見: https://docs.python.org/2/library/csv.html#csv.reader 「每行從CSV文件讀取返回一個字符串列表」

所以,你應該嘗試爲你的第一列:

list = [] 
with open('D:\GIS\Sentinel\cmd_output.txt', 'r') as file: 
    reader = csv.reader (file, delimiter = ' ') 
    for row in reader: 
     list.append(row[0]) 
print list 
+1

這個工作,我認爲比Rhaul KP的答案更快。 – Litwos

+0

很高興幫助! – Daneel

1

你可以用基本split這樣實現這一點。

file_pointer = open('a.txt') 
text = file_pointer.read() 
major_list = [] 
filtered_list = [i for i in text.split('\n') if i] 
for item in filtered_list: 
    major_list.append(item.split()) 
first_row = [item[0] for item in major_list] 
second_row = [item[1] for item in major_list] 
#As may you want. 
相關問題