文件不需要的换行符。当条目过满/过长时写入CSV

2024-10-02 08:24:52 发布

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

我试图用pythons file.write编写一个CSV文件,但是有些索引项太长,以至于它们在CSV文件中产生了新行。我正在使用.format()方法在循环中用它们各自的输入填充我的列。理想情况下,我希望CSV接受长条目,只需更改列宽,而不是将它们插入新行

with tf.Session(config=sess_config) as sess:
        ...

        fclog = open(os.path.join(log_dir, args.fpred + '.csv'), 'w')   # Initialize csv with col headers
        fclog.write("fname,itp,tp_prob,its,ts_prob\n")

        for i in range(len(fname_batch)):
               fclog.write(
               "{},{},{},{},{}\n".format(fname_batch[i].decode(), picks_batch[i][0][0], picks_batch[i][0][1],
                                                picks_batch[i][1][0], picks_batch[i][1][1]))
        ...
        fclog.close()

![Sample rows of csv output

上图是结果csv文件中的行示例。请注意,第一行条目并没有过满,并且工作正常。但是,第二行的条目在tp_prob列中包含一个过满的条目,并将其余条目添加到新行。第三行条目再次按预期工作

谢谢大家!


Tags: 文件csvconfigformatwithbatch条目fname
1条回答
网友
1楼 · 发布于 2024-10-02 08:24:52

我发现,由于某种原因,当数据太长而不是仅仅在行的末尾时,换行符\n被添加到实际的行字符串中。为了解决这个问题,我使用了.replace函数来替换行字符串中的换行符,然后在行的末尾添加了一个换行符

with tf.Session(config=sess_config) as sess:
        ...

        fclog = open(os.path.join(log_dir, args.fpred + '.csv'), 'w')   # Initialize csv with col headers
        fclog.write("fname,itp,tp_prob,its,ts_prob\n")

        for i in range(len(fname_batch)):
               my_str = "{},{},{},{},{}".format(fname_batch[i].decode(), picks_batch[i][0][0],
                                                picks_batch[i][0][1],
                                                picks_batch[i][1][0],
                                                picks_batch[i][1][1]).replace("\n", "")
               fclog.write(my_str + "\n")
        ...
        fclog.close()

我相信有一个更干净的方法可以做到这一点,所以我欢迎更多的解决方案。我也不明白为什么这些换行符会自动插入

相关问题 更多 >

    热门问题