不需要的换行,当条目太满/太长时写CSV

问题描述 投票:0回答:1

我正在尝试使用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列中包含一个过多的条目,并将其余条目推到新行。第三行的条目将再次按预期方式工作。

谢谢!

python python-3.x csv format newline
1个回答
0
投票

我发现由于某种原因,当数据太长而不是仅仅在行尾时,在实际的行字符串中添加了换行符\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()

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

© www.soinside.com 2019 - 2024. All rights reserved.