需要使用php和linux通过行将大csv文件拆分为多个文件。
CSV包含-
"id","name","address"
"1","abc","this is test address1 which having multiple newline
separators."
"2","abc","this is test address2
which having multiple newline separators"
"3","abc","this is test address3.
which having multiple
newline separators."我使用linux拆分的-l 5000测试文件。
但是它不能以正确的格式拆分csv,因为csv中有一个字段地址,有多个换行符,所以命令从该行分割文件。
我还尝试使用PHP:
$inputFile = 'filename.csv';
$outputFile = "outputfile";
$splitSize = 5000;
$in = fopen($inputFile, 'r'):
$header = fgetcsv($in);
$rowCount = 0;
$fileCount = 1;
while (!feof($in)) {
if (($rowCount % $splitSize) == 0) {
if ($rowCount > 0) {
fclose($out);
}
$filename = $outputFile . $fileCount++;
$out = fopen($filename .'.csv', 'w');
chmod($filename,777);
fputcsv($out, $header);
}
$data = fgetcsv($in);
if ($data) {
fputcsv($out, $data);
$rowCount++;
}
}
fclose($out);如何解决这个问题?
发布于 2014-08-11 10:45:09
使用Ruby:
ruby -e 'require "csv"
f = ARGV.shift
CSV.foreach(f).with_index{ |e, i|
File.write("#{f}.#{i}", CSV.generate_line(e, force_quotes: true))
}' file.csvPhp:
<?php
$inputFile = 'file.csv';
$outputFile = 'file.out';
$splitSize = 1;
if (($in = fopen($inputFile, 'r'))) {
$header = fgetcsv($in);
$rowCount = 0;
$fileCount = 0;
while (($data = fgetcsv($in))) {
if (($rowCount % $splitSize) == 0) {
if ($rowCount > 0) {
fclose($out);
}
$filename = $outputFile . ++$fileCount . '.csv';
$out = fopen($filename, 'w');
chmod($filename, 755);
fputcsv($out, $header);
}
fputcsv($out, $data);
$rowCount++;
}
fclose($out);
}
?>发布于 2016-04-21 13:33:33
Linux有一个叫做split的小实用程序,它可以将文件分割成任意大小的块(如100行块)。
但是,对于CSV文件等,每个块通常需要在其中包含标题行。不幸的是,拆分命令没有选项可供选择。但是,只要使用更多的代码,就可以实现它。
tail -n +2 file.txt | split -l 4 - split_
for file in split_*
do
head -n 1 file.txt > tmp_file
cat $file >> tmp_file
mv -f tmp_file $file
donehttps://stackoverflow.com/questions/25241018
复制相似问题