[英]exporting a dataset into a text file in python
I have a list like this example: 我有一个像这样的例子列表:
mylist = ['chr10 30930000 32110000 ARHGAP12,PFKP,ZEB1,ZNF438 4', 'chr15 76430000 77240000 ETFA,ISL2, 4']
I am trying to export it into a text file
. 我正在尝试将其导出到
text file
。 in fact every string would be one line
and every line would have 5 columns
. 实际上,每个
string would be one line
并且every line would have 5 columns
。 every space separated part
in every string would be one column
. 每个字符串中每个
space separated part
将是one column
。 so, in column 4
there are some comma separated characters
and they will be in the same column
. 因此,在第
column 4
有一些comma separated characters
,它们将in the same column
。 and the file would be tab separated
. 和文件将被
tab separated
。
for the example, the expected output would look like this: 对于该示例,预期输出将如下所示:
chr10 30930000 32110000 ARHGAP12,PFKP,ZEB1,ZNF438 4
chr15 76430000 77240000 ETFA,ISL2 4
i am doing that in python
using the following code: 我正在使用以下代码在
python
做到这一点:
with open('outfile.txt', "w") as f:
for item in mylist:
f.write("%s\n" % item+ '\t')
but it does not return exactly what i want. 但是它并没有完全返回我想要的。 do you know how to fix it?
你知道如何解决吗?
Instead of: 代替:
f.write("%s\n" % item+ '\t')
Join by tabs after splitting by whitespace: 按空格分割后按标签加入:
f.write('\t'.join(item.split()) + '\n)
This should be fairly simple as follows - 这应该非常简单,如下所示:
aa=['chr10 30930000 32110000 ARHGAP12,PFKP,ZEB1,ZNF438 4', 'chr15 76430000 77240000 ETFA,ISL2, 4']
with open("aa.txt","w") as wr:
for item in aa:
wr.write("\t".join(item.split(" ")) + "\n")
Each of your item
is a string eg 'chr10 30930000 32110000 ARHGAP12,PFKP,ZEB1,ZNF438 4'
. 您的每个
item
都是一个字符串,例如'chr10 30930000 32110000 ARHGAP12,PFKP,ZEB1,ZNF438 4'
。 I think you'd like to convert the spaces between each column values to tabs. 我想您希望将每个列值之间的空格转换为制表符。 To achive that you should add another nested loop.
为了达到这一目的,您应该添加另一个嵌套循环。 Something like this:
像这样:
with open('outfile.txt', "w") as f:
for line in mylist:
for item in line.split(' '):
f.write(item + '\t')
f.write("\n")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.