[英]Read line by line and then split each object of each line - python3
I am starting using python and lately, I have been struggling with python. 我开始使用python,最近,我一直在努力使用python。 I have the following txt document:
我有以下txt文件:
A001 A001.bam A001.bai
A002 A002.bam A002.bai
A003 A003.bam A003.bai
A005 A005.bam A005.bai
A006 A006.bam A006.bai
I would like to read each line and create a list of list. 我想阅读每一行并创建一个列表列表。 Such as:
如:
[[A001 A001.bam A001.bai][A002 A002.bam A002.bai][A003 A003.bam
A003.bai][A005 A005.bam A005.bai][A006 A006.bam A006.bai]]
Then, I would like to separe each object of each line. 然后,我想分开每一行的每个对象。 Kind of following this example:
以下示例的种类:
a,b,c = x.split(“,”)
a,b,c = x.split(“,”)
a 'blue'
一个“蓝色”
b 'red'
b'红色'
c 'green'
c“绿色”
So it would end up looking kind of: 所以最终看起来像是:
a 'A001'
b 'A001.bam'
c 'A001.bai'
This is as far as I have arrived: 就我所知:
file = open("path_to_file/file.txt")
map = file.read().splitlines()
samp = []
for line in map:
samples = line.split(" ")
samp.append(samples)
samp[line].split(" ")
print(samp)
But it does not work and I am getting very confused. 但这不起作用,我感到非常困惑。 Could someone help this beginner?
有人可以帮助这个初学者吗?
Thanks in advance 提前致谢
You could use zip
with your keys to create a list of objects from your file: 您可以将
zip
与键一起使用,以从文件创建对象列表:
with open('test.txt') as f:
arr = [dict(zip(['a', 'b', 'c'], line.split())) for line in f]
print(arr)
Output: 输出:
[{'a': 'A001', 'b': 'A001.bam', 'c': 'A001.bai'}, {'a': 'A002', 'b': 'A002.bam', 'c': 'A002.bai'}, {'a': 'A003', 'b': 'A003.bam', 'c': 'A003.bai'}, {'a': 'A005', 'b': 'A005.bam', 'c': 'A005.bai'}, {'a': 'A006', 'b': 'A006.bam', 'c': 'A006.bai'}]
I believe that you were wanting to maintain it as a list of lists to do that you just need to remove one line from your code. 我相信您希望将其维护为列表列表,而只需要从代码中删除一行即可。
file = open("path_to_file/file.txt")
map = file.read().splitlines()
samp = []
for line in map:
samples = line.split(" ")
samp.append(samples)
print(samp)
file.close()
But you can simplify it a bit by doing this as you can directly loop through the lines of a file: 但是您可以通过这样做来稍微简化一下,因为您可以直接在文件的各行中循环:
with open("filename") as file:
samp = []
for line in file:
samp.append(line.split(" "))
print(samp)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.