Python文本转list
1 [admin@pe-jira python]$ cat a.txt IPhone MACbook Xiaomi OPPO Coffee TESLA BMW_car bike [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", "copyright", "credits" or "license" for more information. >>> 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 6600 MACbook 8000 Xiaomi 1999 OPPO 2799 Coffee 35 TESLA 870000 BMW_car 340000 bike 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", "copyright", "credits" or "license" for more information. >>> result=[] >>> fd = open( "user_list", "r" ) >>> >>> 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']] >>>