I have some large files in CSV format that I would like to turn into objects using the Import-Csv
command in Powershell. The files are missing the column headings however and these need to be added before I use Import-Csv
. What is the fastest and most efficient way of adding these to the file?
views:
183answers:
3
+5
A:
Prepending to a large file is not an easy or quick operation.
However, import-csv does have a "header" argument that you can use to specify the column headers, i.e.:
$header = 'Foo', 'Bar', 'Baz'
import-csv .\myfile.csv -header $header
Michael
2009-03-18 22:32:18
I think the -header argument is only available in PowerShell V2.
aphoria
2009-03-19 13:54:40
A:
Copy the string you want to prepend to a new file then concatenate the rest to that new file.
Jay
2009-03-18 22:53:28
+1
A:
I'm sure there is a way to do this in one line, but this will work.
Assuming you have Test.csv with these contents:
1,2,3
4,5,6
7,8,9
This PowerShell code will create a new file, NewTest.csv, with column names and append the contents of Test.csv.
Add-Content -path .\NewTest.csv -value "Col1,Col2,Col3"
$contents = Get-Content .\Test.csv
Add-Content -path .\NewTest.csv -value $contents
I can't speak to the performance of this if you have a really large file, but I'm not aware of any other way to do this.
aphoria
2009-03-19 13:49:19
To speed things up a bit, pipe the Get-Content to Add-Content: Get-Content .\Test.csv | Add-Content -path .\NewTest.csv
JasonMArcher
2009-03-24 21:54:24