python - 将 writerow 与数字一起使用

标签 python csv

我正在开发的函数,应该在每次调用时添加新的一行字符串和数字分隔符。
我将一个字符串和一个数字列表作为函数的参数传递。
目前,当函数调用时,它仅将参数写入如下:

[1.0, 2.0, 3.0]

但是,我希望函数编写如下所示分隔的代码:

1.0     2.0     3.0

看起来,我不太理解 writerow 函数。所以我的问题是,如何分隔传递给 writerow 的数字列表?

    # writes the results to a csv file
    # each row contains a string and three numbers
    def write_to_file(file_name, n_t_argument):
        with open(file_name + '.txt', 'a', newline='') as outputfile:
            wrtr  = csv.writer(outputfile, dialect = 'excel-tab')
            text_input = [ n_t_argument ]
            wrtr.writerow(text_input)

    write_to_file('output', [1.0, 2.0, 3.0])

最佳答案

您将数字放入一个嵌套列表中,即列表中的列表。无需这样做:

def write_to_file(file_name, n_t_argument):
    with open(file_name + '.txt', 'a', newline='') as outputfile:
        wrtr  = csv.writer(outputfile, dialect = 'excel-tab')
        wrtr.writerow(n_t_argument)

关于python - 将 writerow 与数字一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15937052/

相关文章:

python - 循环并添加到列表

python - 逻辑回归 - ValueError : classification metrics can't handle a mix of continuous-multi output and binary targets

python - google.api_core.exceptions.Unknown : None There was a problem opening the stream. 尝试打开 DEBUG 级别日志以查看错误

python - 逗号 csv 文件后的最后一个值

ruby - 在 ruby​​ 中解析大型 CSV 文件的最佳方法

java - 如何使用opencsv读取没有标题的csv文件?

python - 将用户输入与关键字列表进行比较

python - 配置 nginx 和 uwsgi 时出现 'No such file or directory' 错误

python - psycopg2 - 字段 "id"缺少数据时出错?

mysql - 使用 SQL 查询以 CSV 格式导出 WordPress 帖子和元信息