首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >复制以空格分隔的字符串列以列表

复制以空格分隔的字符串列以列表
EN

Stack Overflow用户
提问于 2016-07-27 10:02:21
回答 2查看 48关注 0票数 0

我试图将以空格分隔的.txt文件的内容复制到与列对应的单独列表中,但我找不到解决这个问题的方法。

.txt文件的示例如下:

代码语言:javascript
复制
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

如果使用空格分隔符拆分文件,则列将是(在某些列中包含逗号):

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

我尝试做的是(例如第一列):

代码语言:javascript
复制
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:需要超过一个值才能解包

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-07-27 10:13:42

您的reader变量没有您认为的形状,请参见:https://docs.python.org/2/library/csv.html#csv.reader“从csv文件中读取的每一行都作为字符串列表返回。”

因此,您可能应该尝试第一篇专栏文章:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2016-07-27 10:15:18

您可以使用这样的基本split来实现这一点。

代码语言:javascript
复制
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.
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38609794

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档