Python操作与文本文件中的分隔文本

Chr*_*ung 0 python text delimited-text

我有一个名为"test.txt"的文本文件,其中包含此格式的行.

a|b|c|d
a1|b1|c1|d1
a2|b2|c2|d2
a3|b3|c3|d3
Run Code Online (Sandbox Code Playgroud)

我的目的是从该文件中读取并列出列表.结果将是这样的.

[[a,b,c,d],[a1,b1,c1,d1],[a2,b2,c2,d2],[a3,b3,c3,d3]]
Run Code Online (Sandbox Code Playgroud)

我试过这种方式:

myfile=open('test.txt','r')
x=myfile.readlines()
mylist=[]
mylist2=[]
mylist3=[]

for i in range(len(x)):   
   mylist.append(x[i])

for i in range(len(mylist)):
    mylist2.append(mylist[i].strip())
    mylist3.append(mylist2[i].split('|'))
print mylist3
Run Code Online (Sandbox Code Playgroud)

即使我的代码工作没有任何问题,我想知道是否有更好的方法(最好更短)来做它?

Mar*_*ers 5

使用csv模块:

import csv

with open('test.txt','rb') as myfile:
    mylist = list(csv.reader(myfile, delimiter='|'))
Run Code Online (Sandbox Code Playgroud)

即使没有模块,您也可以直接拆分行,而无需始终将结果存储在中间列表中:

with open('test.txt','r') as myfile:
    mylist = [line.strip().split('|') for line in myfile]
Run Code Online (Sandbox Code Playgroud)

两个版本都会导致:

>>> with open('test.txt','rb') as myfile:
...     mylist = list(csv.reader(myfile, delimiter='|'))
... 
>>> mylist
[['a', 'b', 'c', 'd'], ['a1', 'b1', 'c1', 'd1'], ['a2', 'b2', 'c2', 'd2'], ['a3', 'b3', 'c3', 'd3']]
>>> with open('test.txt','r') as myfile:
...     mylist = [line.strip().split('|') for line in myfile]
... 
>>> mylist
[['a', 'b', 'c', 'd'], ['a1', 'b1', 'c1', 'd1'], ['a2', 'b2', 'c2', 'd2'], ['a3', 'b3', 'c3', 'd3']]
Run Code Online (Sandbox Code Playgroud)

  • 使用`csv`的+1(我只使用`mylist = list(reader)`) (2认同)

Ash*_*ary 5

你可以str.splitlist comprehension这里使用.

with open(test.txt) as f:                                                  
    lis = [line.strip().split('|') for line in f]
    print lis
Run Code Online (Sandbox Code Playgroud)

输出:

[['a', 'b', 'c', 'd'], ['a1', 'b1', 'c1', 'd1'], ['a2', 'b2', 'c2', 'd2'], ['a3', 'b3', 'c3', 'd3']]
Run Code Online (Sandbox Code Playgroud)