从字典以csv格式写入输出

2024-06-16 08:30:17 发布

您现在位置:Python中文网/ 问答频道 /正文

请告诉我如何将输出写入制表符分隔格式好吗?我正在比较csv文件和字典。这是我的代码(这是我有问题的代码的结尾):

import csv

file3 = open(r'file.csv','rt', newline = '')
baits = csv.reader(file3, delimiter = '\t')

file4 = open(r'file.txt','wt', newline = '')
common = csv.writer(file4, delimiter = '\t')

for line in baits:
    chromosome = line[0]
    start = int(line[1])
    end = int(line[2])
    if chromosome in dmc:
        for value in dmc[chromosome]:
            base = value[0]
            others = value[1:]
            if base >= start and base <= end:
                count_in += 1
                common.writerow(line + [base, others])

file3.close()
file4.close()

以下是我的输出示例:

chr1    3505353 3505472 3505390 (['3505390', '-', '3.32682966730502e-08', '1.69470366570212e-07', '-35.4239256678281', '1', '156190', 'NM_001011874', '-'],)                                        
chr1    3601312 3601671 3601347 (['3601347', '-', '1.94815734655407e-08', '1.01925267518696e-07', '-40.8010680907877', '2', '60233', 'NM_001011874', '-'],)                                     

我在尝试删除大括号和“”时遇到问题,因此大括号中的每个值都是制表符分隔的。你知道吗

有人知道代码可以被修改来实现这一点吗?你知道吗

谢谢!你知道吗


Tags: csv代码inbasevaluelinenewlineopen
2条回答

我猜是因为你的问题缺少很多信息,你需要改变这一行:

            common.writerow(line + [base, others])

对此:

            common.writerow(line + list(value))

而且,csv文件应该以'rb''wb'模式打开。你知道吗

在这里看不到你的数据很难判断,但我猜是这样的:

line = ['chr', 3505353, 3505472]
base = 3505390
others = (['3505390', '-', '3.32682966730502e-08', '1.69470366570212e-07', '-35.4239256678281', '1', '156190', 'NM_001011874', '-'],)

如果是这样,line + [base, others]将是:

['chr', 3505353, 3505472, 3505390,  (['3505390', '-', '3.32682966730502e-08', '1.69470366570212e-07', '-35.4239256678281', '1', '156190', 'NM_001011874', '-'],)]

换句话说,五列,最后一列是一个元组,其中包含一个列表,其中包含一组值。你知道吗

我不知道您想要什么输出,但是我假设元组中的每个列表都意味着一个新行,而列表只是一堆额外的列。在这种情况下:

if base >= start and base <= end:
    count_in += 1
    for other in others:
        common.writerow(line + [base] + others)

这会给你一行看起来像:

chr1    3505353 3505472 3505390 3505390 - 3.32682966730502e-08 1.69470366570212e-07 -35.4239256678281 1 156190 NM_001011874 -

无论如何,获取所需输出的唯一方法是获取列值列表。而且调试一个正确的列表要容易得多。试着把这些部分打印出来,然后计算出你要做什么才能把这些部分放在一个单一的平面列表中。一旦你做到了,你就完了。你知道吗

相关问题 更多 >