计算CSV文件中的行并将结果导出到CSV [英] Count Rows in CSV files and export results to CSV

查看:51
本文介绍了计算CSV文件中的行并将结果导出到CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算文件夹中一堆CSV中包含值的行.我设法获得了对其进行计数的代码,但似乎找不到找到将结果导出到CSV的方法.我只得到一个空白CSV.

I am trying count the rows containing values in a bunch of CSV in a folder. I managed to get the code to count it but I can't seem to find a way to export the results to a CSV. All I got is a blank CSV.

我在这里想念什么?

$FOLDER_ROOT = "C:\Test\2019"
$OUTPUT_CSV = "C:\Test\2019\Count.csv"

Get-ChildItem $FOLDER_ROOT -re -in "*.csv" | ForEach-Object {
    $filestats = Get-Content $_.Fullname | Measure-Object -Line
    $linesInFile = $filestats.Lines - 1
    Write-Host "$_,$linesInFile"
} | Export-Csv -Path $OUTPUT_CSV -NoType

推荐答案

您的代码有几个问题:

  • 使用 Get-ChildItem -Filter'* .csv'代替 Get-ChildItem -Include'* .csv'.前者比后者快.

Write-Host 最有可能导致输出直接进入主机控制台.有人告诉我这在最新版本中已更改(以便主机输出进入新的信息流),但是对于至少在v5之前的版本,这仍然是现实.

Write-Host most likely causes the output to go directly to the host console. I've been told that this was changed in recent versions (so that host output goes to the new information stream), but for versions at least prior to v5 it's still a reality.

Export-Csv 需要对象输入,因为它将对象的属性输出为CSV的字段(从第一个对象的属性名称获取列标题).向其提供字符串("$ _,$ linesInFile" )将导致CSV仅包含列"Length",因为这是字符串对象的唯一属性.

Export-Csv expects object input, since it outputs the properties of the objects as the fields of the CSV (taking the column titles from the property names of the first object). Feeding it strings ("$_,$linesInFile") will result in a CSV that contains only a column "Length", since that is the only property of the string objects.

使用计算出的属性来创建包含文件名的CSV和输入文件的行数:

Use a calculated property for creating a CSV with the filename and line count of the input files:

Get-ChildItem $FOLDER_ROOT -Recurse -Filter '*.csv' |
    Select-Object Name, @{n='LineCount';e={(Get-Content $_.Fullname | Measure-Object -Line).Lines - 1}} |
    Export-Csv $OUTPUT_CSV -NoType

这篇关于计算CSV文件中的行并将结果导出到CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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