0

我正在尝试使用 csv.reader() 从数据库中提取值以供以后比较。我想让读者索引该行,以便列表中的每个元素对应一个逗号分隔值,而不是该行中的字符。

我的代码:

with open(sys.argv[1]) as str_db:
    str_reader = csv.reader(str_db)
    line_count = 0
    fields = []
    for row in str_db:
        if line_count == 0:
            fields = re.split(",", row)
            line_count += 1
        else:
            print(f"{fields[0]}: {row[0]}, {fields[1]}: {row[1]}, {fields[2]}: {row[2]}, {fields[3]}: {row[3]}")

从文件中拉取 = argv[1]:

name,AGATC,AATG,TATC
Alice,2,8,3
Bob,4,1,5
Charlie,3,2,5

我希望看到的地方:

name: Alice, AGATC: 2, AATG: 8, TATC: 3
name: Bob, AGATC: 4, AATG: 1, TATC: 5
name: Charlie, AGATC: 3, AATG: 2, TATC: 5

相反,这是我的输出:

name: A, AGATC: l, AATG: i, TATC
: c
name: B, AGATC: o, AATG: b, TATC
: ,
name: C, AGATC: h, AATG: a, TATC
: r

如果您能告诉我为什么在 TATC 末尾开始新行,则非常感谢。

我试过了:

with open(sys.argv[1]) as str_db:
    str_reader = csv.reader(str_db, delimiter = ',')
    line_count = 0
    fields = []
    for row in str_db:
        if line_count == 0:
            fields = re.split(",", row)
            line_count += 1
        else:
            print(f"{fields[0]}: {row[0]}, {fields[1]}: {row[1]}, {fields[2]}: {row[2]}, {fields[3]}: {row[3]}")

但没有变化。

4

1 回答 1

0

实际上使用阅读器会产生正确的结果。建议使用和newline=''打开文件:csv.readercsv.writer

import csv

with open('input.csv',newline='') as str_db:
    reader = csv.reader(str_db)
    fields = next(reader)
    for row in reader:
        print(f"{fields[0]}: {row[0]}, {fields[1]}: {row[1]}, {fields[2]}: {row[2]}, {fields[3]}: {row[3]}")

输出:

name: Alice, AGATC: 2, AATG: 8, TATC: 3
name: Bob, AGATC: 4, AATG: 1, TATC: 5
name: Charlie, AGATC: 3, AATG: 2, TATC: 5

DictReader可以帮助一点:

import csv

with open('input.csv') as str_db:
    reader = csv.DictReader(str_db)
    for row in reader:
        print(', '.join([f'{key}: {value}' for key,value in row.items()]))

(相同的输出)

于 2020-06-30T21:21:59.927 回答