【问题标题】:It takes about 10 minutes to prepend header to a 100MB file将标头添加到 100MB 文件大约需要 10 分钟
【发布时间】:2021-02-10 21:48:51
【问题描述】:

将标题添加到文件的最快方法是什么? 占用了 100 兆字节的文件 约10分钟 将标题添加到文件中。 在java中需要两秒钟。

下面的例子很慢:

$header = 'address;name'
Import-Csv .\myfile.csv -Header $header

或

Add-Content -path .\NewTest.csv -value "address;name"
$contents = Get-Content .\Test.csv
Add-Content -path .\NewTest.csv -value $contents

【问题讨论】:

  • 如果你想知道哪一个更快,你为什么不试试两者并测量它需要多长时间? Measure-Command is your friend
  • 如果您想使用 Import-Csv 执行此操作,您需要使用 -Delimiter ';' 指定您的 csv 使用分号作为分隔符
  • PowerShell 与 Java 不同,后者针对流式传输(管道使用)进行了优化。通常,尽量避免将整个表加载到内存中(不要将其分配给变量)。相反,直接将每个对象通过管道传递到下一个 cmdlet 并最终从内存中卸载它:import-csv .\myfile.csv | foreach-object { 为每个项目做你的事情} | export-csv .\output.csv(请添加更多关于你尝试实现的细节)跨度>
  • 归根结底,您无法通过对某些单独命令 as the performance of a complete (PowerShell) solution is supposed to be better than the sum of its parts 求和来证明 PowerShell 的性能。换句话说,这取决于您要对每个项目执行的操作可能需要比加载和卸载单个项目的开销更长的时间,请参阅Advocating native PowerShell

标签: powershell


【解决方案1】:

怎么样

Set-Content -Path 'D:\Test\NewTest.csv' -Value "address;name"
[System.IO.File]::AppendAllText('D:\Test\NewTest.csv', [System.IO.File]::ReadAllText('D:\Test\Test.csv'))

您需要为此使用完整的绝对路径

【讨论】:

  • 最后一个例子删除文件的内容
  • @gavinnewsom 恐怕你评论错了答案..
【解决方案2】:

使用 .NET 方法处理文件内容通常比 PowerShell cmdlet 更快,因为它们有很多开销等。(查看this performance comparison)

这是一个简短的版本:

$path = (Get-Item .\myfile.csv).FullName
$contents = [System.IO.File]::ReadAllText($path)
Set-Content -Path $path -Value "address;name"
[System.IO.File]::AppendAllText($path, $contents)

这是另一个可能的示例,它一次处理一行,而不是一次读取整个文本,因此更容易记忆。

# your original file
$instream = New-Object System.IO.StreamReader "c:\test\myfile.csv"
# new temporary file
$outstream = New-Object System.IO.StreamWriter "c:\test\myfile2.csv"
# write the header
$outstream.WriteLine("address;name")
# write remaining contents
foreach ($line in $instream.ReadLine()) {
    $outstream.WriteLine($line)
}
$instream.Dispose()
$outstream.Dispose()

# replace the old file
Remove-Item "c:\test\myfile.csv"
Rename-Item "c:\test\myfile2.csv" "myfile.csv"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    • 2015-07-16
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    相关资源
    最近更新 更多