将列表转换为整数并使用Python存储为csv文件

2024-03-29 12:39:38 发布

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

我在列表中生成了一些数据。我已经创建了一个csv文件,它在csv中附加数据文件。但是我需要将数据存储为整数/string而不是列表。我的代码如下:

VALUE = list(map(int, VALUE))
print(name, VALUE)
with open("data.csv", "a") as out_file:
        out_string =  ""
        out_string +=  "" + name
        out_string +=  "," + str(VALUE)
        out_string += "\n"
        out_file.write(out_string)

输出文件是:enter image description here

我需要删除第2列和第17列中生成的[]。我不知道怎么做。你知道吗


Tags: 文件csv数据代码namemap列表string
3条回答

您正在打印一个整数数组,如下所示:

>>> x = [1,2,3]
>>> print(str(x))
[1, 2, 3]
>>>

方括号是Python打印数组的方法。要将它们打印为CSV行,请将元素转换为字符串,并用逗号连接它们:

out_string +=  "," + ",".join([str(i) for i in VALUE])

VALUE(为什么大写,它不是常量?)如果一个list有两个int类型的元素和值15342str(VALUE)将是[153,42]。当您希望输出是153,42时,可以使用','.join(VALUE),它将连接列表中的元素,由str分隔,在这里您调用join方法,在这里是逗号。你知道吗

但是,在编写.csv文件时,您可能还需要考虑使用Python标准库中的csv模块。你知道吗

在您的案例中,out_string的数据类型是list,它为您提供list列表。要转换,您可以使用join,它将数据类型转换为str,并将list的元素连接到您的case中的“”。你知道吗

VALUE = list(map(int, VALUE))
print(name, VALUE)
with open("data.csv", "a") as out_file:
    out_string =  ""
    out_string +=  "" + name
    out_string +=  ",".join(VALUE)
    out_string += "\n"
    out_file.write(out_string)`

我想它现在会给你想要的输出。你知道吗

相关问题 更多 >