我想在windows中使用python将csv文件转换为dos2unix格式。对了现在我正在手动操作,将csv文件放在工作区(服务器)中,并在putty.Command中运行命令: dos2unix file_received filename
发布于 2019-10-13 19:43:46
dos2unix (我记得)几乎只去掉了每一行的尾随换行符。因此,有两种方法可以做到这一点。
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,人们可能会将可执行命令标记到该参数中。
import subprocess
subprocess.call([ 'dos2unix', file_received, filename, shell=False])我还没有测试过上面的内容。shell=False (缺省值)意味着进程不会调用UNIX shell。这有助于避免有人将命令插入到参数中,但您可能必须拥有shell=True才能使命令正确工作。
发布于 2019-10-13 20:03:15
下面的代码可以做到这一点:
import csv
out_file_path =
in_file_path =
with open(out_file_path,'w',newline='') as output_file:
writer = csv.writer(output_file, dialect=csv.unix_dialect)
with open(in_file_path,newline='') as input_file:
reader = csv.reader(input_file)
for row in reader:
writer.writerow(row)https://stackoverflow.com/questions/58363093
复制相似问题