使用powershell读取文本文件,在将每个文本文件输出到CSV文件之前编辑一个列



我有一批需要转换为csv文件的文本文件。但是,一旦打开csv文件,列中的数据就被转换为科学符号。我想通过编辑列并在输出到最终csv之前插入撇号来防止这种情况。我在网上找到的大多数建议都包括首先定义所有的列/标题。这个解决方案并不理想,因为不同的文本文件有不同的头文件。但是,所有文件都有一个名为"account"的Column。这是我唯一想编辑的专栏。

获取文本并输出到csv的脚本:

$path = "C:Test*.txt"
$files = Get-ChildItem $path | where { ! $_.PSIsContainer }
foreach ($file in $files){
$newFileName = ($file.Fullname) -Replace ".txt",".csv"
Import-Csv $file.FullName |Export-Csv $newFileName -NoTypeInformation 
}
到目前为止,我已经能够像这样编辑列了
$acct = (Import-Csv $file).acct
$acct ="'"+ $acct

我正在努力将这些组合起来,以便我的输出$newfilename将编辑值存储在"帐户"列。任何建议都是受欢迎的,如果有其他方法可以转换这些文件并防止数据变成科学符号,我都支持。

当我尝试组合我的代码时,例如通过管道$ account到export-csv,通常我最终得到的输出是一个只有以下内容的csv文件:"Length"34";编辑:我正在更新我正在处理的数据样本。原始文件包含167列,我认为我不能在这里以一种清晰的方式发布。

data_id、地点placepool_id,帐目,sec_acct, ter_acct, source_acct product_id123 a0001234567, 00, 12345、1234567890123456、1234567890123456……123,

123 a0001234567 00, 12345年1.23457 e + 15, 9.87654 e + 15…123年,

我想编辑数据,以防止任何信息被转换为科学符号。

继续我的评论:

  • 要阻止Excel在导入数据时转换您的数值,您可以在其值前添加TAB字符。然后Excel将其读取为文本
  • 当使用Export-Csv保存更新的数据时,您可以附加开关-UseCulture,因此所使用的分隔符字符是从设置为本地ListSeparator字符的任何字符中选择的。Excel期望通过双击打开文件,这样您就不必使用导入向导。(查看系统中设置的字符,使用(Get-Culture).TextInfo.ListSeparator)
$path = 'C:Test'
$files = Get-ChildItem $path -File -Filter '*.txt'
foreach ($file in $files) {
$data = Import-Csv -Path $file.FullName
foreach ($row in $data) {
# prepend a TAB character in front of the field you want Excel to 
# treat as string as opposed to converting it to scientific value
$row.acct = "`t{0}" -f $row.acct
# you can do the same here for fields 'data_id', 'sec_acct' etc if needed
}
$newFile = [System.IO.Path]::ChangeExtension($file.Fullname,".csv")
# now save the updated data. With -UseCulture you can simply
# double-click the created csv file to open in Excel on any machine
# that has the same locale setting for the ListSeparator
$data | Export-Csv -Path $newFile -NoTypeInformation -UseCulture
}

所以您使用名称编辑列的想法是正确的。我们只需要一行一行地编辑每个值。幸运的是,我们也能够获得列名,所以它应该工作,而不必手动输入所有的列。我使用了@Theo的建议,在前面加上了"t";到单元格值,它修复了excel以科学记数法显示值的问题。

希望这是一个好的起点。在当前状态下,它可能不是最有效的。

$path = "C:Test*.txt"
$files = Get-ChildItem $path | where { ! $_.PSIsContainer }
foreach ($file in $files){
$newFileName = ($file.Fullname) -Replace ".txt",".csv"
$csv = Import-Csv $file.FullName
# get column names
$columnNames = ($csv[0].psobject.Properties | select Name).Name
# will have to work by row
$rowNum = [int]0
while ($rowNum -lt $csv.count){

# on the row change value for each column
foreach ($column in $columnNames) {


$csv[$rowNum].$column = "`t" +  $csv[$rowNum].$column
}

$rowNum += 1
}

# was running into a bug with powershell on a mac so had to pipe $csv to export-csv instead of using -input-object
$csv | Export-Csv -LiteralPath $newFileName -NoTypeInformation

}