将行保存为csv格式 [英] Save a row to csv format

查看:75
本文介绍了将行保存为csv格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组要保存到csv文件中的数据库行.
考虑到数据是ascii字符,没有任何奇怪的字符,下面的内容就足够了吗?

I have a set of rows from a DB that I would like to save to a csv file.
Taking into account that the data are ascii chars without any weird chars would the following suffice?

my $csv_row = join( ', ', @$row );  
# save csv_row to file    

我担心的是,这是否会创建任何工具都可以接受为CSV的行,例如,不涉及引号等.

My concern is if that would create rows that would be acceptable as CSV by any tool and e.g not be concern with quoting etc.

更新:
这有什么区别吗?

Update:
Is there any difference with this?

my $csv = Text::CSV->new ( { binary => 1, eol    => "\n"} );
my $header = join (',', qw( COL_NAME1 COL_NAME2 COL_NAME3 COL_NAME4 ) );
$csv->print( $fh, [$header] );                                                                             
foreach my $row ( @data ) {  
  $csv->print($fh,  $row );    
}    

这是我的第一行:

" COL_NAME1,COL_NAME2,COL_NAME3,COL_NAME4"   

请注意双引号,其余各行均不带引号.
与普通的 join 有什么区别?我还需要 binary 设置吗?

Please notice the double quotes and the rest of the rows are without any quotes.
What is the difference than my plain join? Also do I need the binary set?

推荐答案

最安全的方法应该是使用逗号分隔符来编写干净的记录.越简单越好,尤其是在现实生活中变化很大的格式中.如果需要 ,请在每个字段双引号.

The safest way should be to write clean records with a comma separator. The simpler the better, specially with the format that has so much variation in real life. If needed, double quote each field.

使用该模块的真正优势在于读取真实"数据.但是,将其也用于编写以及统一的CSV处理方法,是非常有意义的.而且,然后可以以清晰的方式设置选项,并且该模块可以消除数据中的一些小问题.

The true strength in using the module is for reading of "real-life" data. But it makes perfect sense to use it for writing as well, for a uniform approach to CSV. Also, options can then be set in a clear way, and the module can iron out some glitches in data.

Text :: CSV 文档告诉我们有关 binary 选项

The Text::CSV documentation tells us about binary option

重要说明:默认行为是仅接受 0x20 (空格)到 0x7E (波浪号)范围内的ASCII字符.这意味着字段不能包含换行符.如果您的数据包含嵌入在字段中的换行符或 0x7E (波浪号)上方的字符或二进制数据,则您 必须 设置 binary =>1 在对 new 的调用中.为了涵盖最广泛的解析选项,您将始终需要设置二进制.

Important Note: The default behavior is to accept only ASCII characters in the range from 0x20 (space) to 0x7E (tilde). This means that the fields can not contain newlines. If your data contains newlines embedded in fields, or characters above 0x7E (tilde), or binary data, you must set binary => 1 in the call to new. To cover the widest range of parsing options, you will always want to set binary.

我会说用它.由于您编写的是文件,因此可能是 eol (或使用 say 方法)作为选项的文件.但是请扫描许多有用的选项并查看它们的默认值.

I'd say use it. Since you write a file this may be it for options, along with eol (or use say method). But do scan the many useful options and review their defaults.

对于标题, print 方法需要一个数组引用,其中每个字段都是一个元素,而不是包含逗号分隔字段的单个字符串.所以说错了

As for your header, the print method expects an array reference where each field is an element, not a single string with comma-separated fields. So it is wrong to say

my $header = join (',', qw(COL_NAME1 COL_NAME2 COL_NAME3 COL_NAME4));  # WRONG
$csv->print( $fh, [$header] );

因为 $ header 是单个字符串,然后将其作为由 [...] 创建的(匿名)数组引用的唯一元素.因此,它将此字符串打印为该行的第一个字段,并且由于在其中检测到分隔符 本身,因此它也将双引号引起来.相反,您应该拥有

since the $header is a single string which is then made the sole element of the (anonymous) array reference created by [ ... ]. So it prints this string as the first field in the row, and since it detects in it the separator , itself it also double-quotes. Instead, you should have

$csv->print($fh, [COL_NAME1 COL_NAME2 COL_NAME3 COL_NAME4]);

或更好地将列名称分配给 @header ,然后执行 $ csv-> print($ fh,\ @header).

or better assign column names to @header and then do $csv->print($fh, \@header).

这也是使用模块编写代码的原因的一个示例.如果逗号滑入数组的元素(应该是单个字段),则可以通过双引号正确处理它.

This is also an example of why it is good to use the module for writing – if a comma slips into an element of the array, supposed to be a single field, it is handled correctly by double-quoting.

完整的示例

use warnings;
use strict;
use Text::CSV_XS;

my $csv = Text::CSV->new ( { binary => 1, eol => "\n" } ) 
    or die "Cannot use CSV: " . Text::CSV->error_diag();

my $file = 'output.csv';
open my $fh_out , '>', 'output.csv' or die "Can't open $file for writing: $!";

my @headers = qw( COL_NAME1 COL_NAME2 COL_NAME3 COL_NAME4 );
my @data = 1..4;

$csv->print($fh_out, \@headers);
$csv->print($fh_out, \@data);

close $fh_out;

产生文件 output.csv


COL_NAME1,COL_NAME2,COL_NAME3,COL_NAME4
1,2,3,4

这篇关于将行保存为csv格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆