您的当前位置:首页正文

Python文本转list

2022-04-17 来源:年旅网
Python⽂本转list

1

[admin@pe-jira python]$ cat a.txt IPhone MACbookXiaomi OPPOCoffee TESLABMW_carbike

[admin@pe-jira python]$ python

Python 3.6.0a1 (default, Mar 2 2017, 13:43:21) [GCC 4.4.7 20120313 (Red Hat 4.4.7-16)] on linux

Type \"help\>>> rs = []

>>> for ln in open('a.txt','rt'): ... rs.extend(ln.strip().split(' '))... >>> rs

['IPhone', 'MACbook', 'Xiaomi', 'OPPO', 'Coffee', 'TESLA', 'BMW_car', 'bike']>>>

按⾏转成列表

[admin@pe-jira python]$ cat user_list IPhone 6600MACbook 8000Xiaomi 1999OPPO 2799Coffee 35

TESLA 870000BMW_car 340000bike 800

[admin@pe-jira python]$ python

Python 3.6.0a1 (default, Mar 2 2017, 13:43:21) [GCC 4.4.7 20120313 (Red Hat 4.4.7-16)] on linux

Type \"help\>>> result=[]

>>> fd = open( \"user_list\>>>

>>> for line in fd.readlines():... l=list(line.split())... print(l)

... result.append(l)...

['IPhone', '6600']['MACbook', '8000']['Xiaomi', '1999']['OPPO', '2799']['Coffee', '35']

['TESLA', '870000']['BMW_car', '340000']['bike', '800']>>> print(\"----\")---->>> result

[['IPhone', '6600'], ['MACbook', '8000'], ['Xiaomi', '1999'], ['OPPO', '2799'], ['Coffee', '35'], ['TESLA', '870000'], ['BMW_car', '340000'], ['bike', '800']]>>>

因篇幅问题不能全部显示,请点此查看更多更全内容