将空格分隔的字符串列复制到列表
问题描述:
我想将空格分隔的.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
如何为文件中的每个列执行此操作? 谢谢!
答
你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
答
你可以用基本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.
如果您确定您使用了正确的分隔符,那么您会将您的拆包零件包装在“try-except”中,以便处理有缺陷的行。 – Kasramvd
我不知道该怎么做。我不是Python的高级用户。 – Litwos
你能展示实际的追溯?你为什么只是追加一个?它看起来像'产品'的价值? –