问题
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]
回答1:
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)
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])
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.
回答2:
The following code would do the trick:
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/how-to-convert-dos2unix-csv-file-with-python-script