Python-在csv文件

时间:2017-04-09 04:31:24

标签: python csv import

我在csv文件中获得了数据。 然后我使用这些代码将文件导入Python

with open('file.csv') as data:
        reader = csv.reader(data)
        dat = list(reader)

我使用以下代码将“ - ”替换为0

for i in range(len(dat)):
        for j in range (len(dat[0])):
            if dat[i][j] == '-':
                dat[i][j] = 0

然后我得到了类似的东西

dat=[[0,"8","4","10],["",0,"5","6"],["","",0,"9"],["","","",0]]

如何让dat对称并用0替换所有“”,并使“”中的数字成为整数?

预期产出:

dat=[[0,8,4,10],[8,0,5,6],[4,5,0,9],[10,6,9,0]]

非常感谢你!

1 个答案:

答案 0 :(得分:1)

如果要将数据存储在文件中,则需要读取数据并将其写回csv阅读器。

在您的示例中,您应该执行:if dat[i][j] in ('-', "")然后将其写回文件。

实现这一目标的另一种方法是:

with open('file.csv') as data:
    reader = csv.reader(data)
    output = []
    for row in reader:
        output.append([0 if cell in ("", "-") else int(cell) for cell in row])
    print(output)

样本:

>>> output = []
>>> rows = [["", "-", "8", "10"], ["1", "-", "", "100"]]
>>> for row in rows:
...     output.append([0 if cell in ("", "-") else int(cell) for cell in row])
... 
>>> print(output)
[[0, 0, 8, 10], [1, 0, 0, 100]]
>>>