将空格分隔的字符串列复制到列表

时间:2016-07-27 10:02:21

标签: python list

我正在尝试将空格分隔的.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:解包需要多于1个值

如何为文件中的每个列执行此操作? 谢谢!

2 个答案:

答案 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 :(得分: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.