如何使用python脚本转换dos2unix csv文件 [英] How to convert dos2unix csv file with python script

查看:229
本文介绍了如何使用python脚本转换dos2unix csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Windows中使用python将csv文件转换为dos2unix格式. 现在,我正在通过将csv文件放置在工作区(服务器)中并在putty中运行命令来手动进行操作.[命令:dos2unix file_received文件名]

I want to convert a csv file into dos2unix format using python in windows. Rightnow I am doing manually by placing csv file in workarea(server) and run command in putty.[Command : dos2unix file_received filename]

推荐答案

dos2unix(我记得)几乎只去除了每行的尾随换行符.因此,有两种方法可以执行此操作.

dos2unix (as I recall) pretty much only strips the trailing linefeeds off each line. So, there's two ways you can do this.

with open(filename, "w") as fout: 
    with open(file_received, "r") as fin:
        for line in fin:
            line = line.replace('\r\n', '\n')
            fout.write(line)

或者您可以使用子进程直接调用UNIX命令. 警告:这很糟糕,因为您使用的是参数file_received,人们可能会在其中标记可执行命令.

or you can use subprocess to call the UNIX command directly. WARNING: This is bad since you're using a parameter file_received, and people could potentially tag executable commands into it.

import subprocess
subprocess.call([ 'dos2unix', file_received, filename, shell=False])

我还没有测试上述内容. shell=False(缺省值)表示不会为该进程调用UNIX shell.这样做可以避免有人在命令中插入命令,但是为了使命令正确运行,您可能必须具有shell=True.

I haven't tested the above. The shell=False (the default) means a UNIX shell won't be called for the process. This is good to avoid someone inserting commands into the parameters, but you may have to have shell=True in order for the command to work right.

这篇关于如何使用python脚本转换dos2unix csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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