首页 > 解决方案 > 将 Powershell 数据清理代码转换为 Python 代码

问题描述

我想将下面的 Powershell 脚本转换为 Python 代码。

这导致最终文件被管道分隔,数据中没有双引号或逗号。在做这项工作时,我使用了这个顺序,因为如果您在建立管道之前尝试替换双引号和逗号,列和数据将会中断。

Param([string]$RootString,  [string]$Ext)   

$OrgFile = $RootString
$NewFile = $RootString.replace($Ext,"out")

Import-Csv $OrgFile -Encoding UTF8 | Export-Csv tempfile.csv -Delimiter "|" -NoTypeInformation
(Get-Content tempfile.csv).Replace(",","").Replace('"',"") | Out-File $NewFile -Encoding UTF8

Copy-Item -Force $NewFile $OrgFile
Remove-Item –path $NewFile -Force

我为此得到了一点,但是。没有看到发布不起作用的错误代码的意义。这是我的非工作代码版本。

for index in range(len(dfcsv)):
    filename = dfcsv['csvpath'].iloc[index]
    print(filename)
    print(i)
    with open(filename, 'r+') as f:
        text = f.read()
        print(datetime.now())
        text = re.sub('","', '|', text)
        print(datetime.now())
        f.seek(0)
        f.write(text)
        f.truncate()
        i = i + 1

这段代码的问题是查找和替换的方法。由于双引号,这在开始时创建了额外的列。然后有时在末尾有额外的列,因为有时末尾有双引号。这导致来自不同行的数据合并在一起。我没有发布这部分,因为我认为这对我的目标没有必要。更相关的似乎是将工作代码创建为更好的目标概念。这是非工作代码。

标签: pythonpowershellcsv

解决方案


似乎这里没有人想回答问题,所以我在其他地方找到了解决方案。这是需要将逗号文件转换为管道分隔符的任何人的链接: https ://www.experts-exchange.com/questions/29188372/How-can-I-Convert-Powershell-data-clean-up-code-to -Python-Code.html


推荐阅读