如何在PowerShell中将CSV文件拆分为多个纯文本文件?

huangapple go评论54阅读模式
英文:

How to split a CSV file into multiple plain text files in Powershell?

问题

以下是您提供的代码的翻译部分:

我正在尝试将CSV文件Excel正确显示两列和多行拆分为多个纯文本文件每行一个文件我已经做到了这一点

    $InputFilename = Get-Content 'csv-full.csv'
    
    $OutputFilenamePattern = 'output_done_'
    
    $LineLimit = 1
    
    $line = 0
    
    $i = 0
    
    $file = 0
    
    $start = 0
    
    while ($line -le $InputFilename.Length) {
    
    if ($i -eq $LineLimit -Or $line -eq $InputFilename.Length) {
    
    $file++
    
    $Filename = "$OutputFilenamePattern$file.txt"
    
    $InputFilename[$start..($line-1)] | Out-File $Filename -Force
    
    $start = $line;
    
    $i = 0
    
    Write-Host "$Filename"
    
    }
    
    $i++;
    
    $line++
    
    }

请注意,csv-full.csv 是我的文件名。

我使用此方法的问题是它为包含4行的CSV测试文件创建了大量文件,第一个文件是标题,其余的文件有些是空白的,其他的有文本段落,这些段落位于同一行,但我不知道为什么它们被拆分为不同的文件。

请考虑第一列是标题,第二列在某些情况下包含多个段落的文本。文本包括重音字符和符号(文本为西班牙文:áéíóúñ¿?)。真实的CSV文件有数千行。

如果可能的话,请确保输出文件以UTF-8编码。

编辑:

以下是CSV文件中的几行纯文本:

Pregunta,Respuesta
¿Qué es una casa?,"

Una casa es un edificio para habitar. El término suele utilizarse para nombrar a la construcción de una o pocas plantas que está destinada a la vivienda de una única familia, en oposición a los edificios de múltiples departamentos, apartamentos o pisos.

Por ejemplo: “Mi tía vive en una casa con jardín y piscina”, “Me encantaría mudarme a una casa, porque en el departamento me siento como encerrada”, “Los delincuentes ingresaron a la casa y amenazaron al matrimonio”.

"
¿Qué es una pregunta?,"

El término pregunta tiene su origen etimológico en el latín. Y es que fruto de la suma de dos componentes de dicha lengua: el prefijo “pre-“, que significa “antes”, y el verbo “cunctari”, que puede traducirse como “dudar” o “demorar”.

Una pregunta es una interpelación que se realiza con la intención de obtener algún tipo de información. Al pronunciar esta interrogación, se espera recibir una respuesta que incluya los datos buscados.

希望这有助于您的工作。

英文:

I'm trying to split a CSV file (Excel correctly shows two columns and multiple rows) into multiple plain text files. One file for each row. This is how far i got:

$InputFilename = Get-Content 'csv-full.csv'

$OutputFilenamePattern = 'output_done_'

$LineLimit = 1

$line = 0

$i = 0

$file = 0

$start = 0

while ($line -le $InputFilename.Length) {

if ($i -eq $LineLimit -Or $line -eq $InputFilename.Length) {

$file++

$Filename = "$OutputFilenamePattern$file.txt"

$InputFilename[$start..($line-1)] | Out-File $Filename -Force

$start = $line;

$i = 0

Write-Host "$Filename"

}

$i++;

$line++

}

csv-full.csv is the name of my file.

The issue I have with this method is that it creates dozens of files for a 4 row CSV test file, the first file being the header and the rest of files some are blank, others have paragraphs of text that are in the same row, but I don't know why are split into different files.

Please consider that the first column is a title, and the second column is the text in some cases multiple paragraphs. The text includes accented characters and symbols (text is in Spanish: áéíóúñ¿?) The real CSV file has thousands of rows.

如何在PowerShell中将CSV文件拆分为多个纯文本文件?

Thank you. If possible, please that the output files are in UTF-8 encoding

Edit:

These are a few lines of the CSV file as plain text:

Pregunta,Respuesta
¿Qué una casa?,"

Una casa es un edificio para habitar. El término suele utilizarse para nombrar a la construcción de una o pocas plantas que está destinada a la vivienda de una única familia, en oposición a los edificios de múltiples departamentos, apartamentos o pisos.

Por ejemplo: “Mi tía vive en una casa con jardín y piscina”, “Me encantaría mudarme a una casa, porque en el departamento me siento como encerrada”, “Los delincuentes ingresaron a la casa y amenazaron al matrimonio”.

"
¿Qué un pregunta?,"

El término pregunta tiene su origen etimológico en el latín. Y es que fruto de la suma de dos componentes de dicha lengua: el prefijo “pre-“, que significa “antes”, y el verbo “cunctari”, que puede traducirse como “dudar” o “demorar”.

Una pregunta es una interpelación que se realiza con la intención de obtener algún tipo de información. Al pronunciar esta interrogación, se espera recibir una respuesta que incluya los datos buscados.

答案1

得分: 1

Sure, here's the translated content:

自从您的CSV文件包含多行字符串,如果不使用CSV解析器,这个任务将变得非常困难。相反,您可以使用 Import-Csv 来读取和解析它,然后使用 Export-Csv 将每一行导出到单独的文件:

$outputfolder = '路径\到\输出文件夹'
Import-Csv 路径\到\输入Csv.csv -Encoding utf8 | ForEach-Object { $i = 0 } {
    $path = Join-Path $outputfolder -ChildPath ('文件名-部分{0:D2}.csv' -f $i++)
    $_ | Export-Csv $path -NoTypeInformation -Encoding utf8
}

至于排除CSV标题,有两个选项,如果您使用 PowerShell 7.4(预览版),您可以简单地使用 -NoHeader,否则,您需要使用 ConvertTo-Csv 然后排除第一行,并使用 Set-Content 进行导出:

$outputfolder = '路径\到\输出文件夹'
Import-Csv 路径\到\输入Csv.csv -Encoding utf8 | ForEach-Object { $i = 0 } {
    $path = Join-Path $outputfolder -ChildPath ('文件名-部分{0:D2}.csv' -f $i++)
    $_ | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Set-Content $path -Encoding UTF8
}
英文:

Since your CSV has multi-line strings doing this without a CSV parser would make the task very difficult, instead you can use Import-Csv to read and parse it then Export-Csv to export each row to a separate file:

$outputfolder = 'path\to\outputFolder'
Import-Csv path\to\inputCsv.csv -Encoding utf8 | ForEach-Object { $i = 0 } {
    $path = Join-Path $outputfolder -ChildPath ('fileName-Part{0:D2}.csv' -f $i++)
    $_ | Export-Csv $path -NoTypeInformation -Encoding utf8
}

As for excluding the CSV Headers, there are 2 options, if you're using PowerShell 7.4 (preview) you can simply use -NoHeader, else, you need to ConvertTo-Csv then exclude the first line and use Set-Content for exporting:

$outputfolder = 'path\to\outputFolder'
Import-Csv path\to\inputCsv.csv -Encoding utf8 | ForEach-Object { $i = 0 } {
    $path = Join-Path $outputfolder -ChildPath ('fileName-Part{0:D2}.csv' -f $i++)
    $_ | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Set-Content $path -Encoding UTF8
}

huangapple
  • 本文由 发表于 2023年3月31日 04:55:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75892925.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定