如何使用python脚本转换dos2unix csv文件 [英] How to convert dos2unix csv file with python script
问题描述
我想在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屋!