1

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

4

2 回答 2

3

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)

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

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

我没有测试过上面的。(shell=False默认值)表示不会为该进程调用 UNIX shell。这可以避免有人在参数中插入命令,但您可能必须这样做shell=True才能使命令正常工作。

于 2019-10-13T11:43:45.903 回答
1

以下代码可以解决问题:

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)
于 2019-10-13T12:03:14.897 回答