SFTP具有字符编码和行结束选项

时间:2016-01-22 22:52:00

标签: python

我正在使用python将文件从一个Linux VM发送到另一个Linux VM,这样做很棒。文件发送成功但发送文件之前,我想将文件编码更改为“UTF-8”,行结束为“Unix / Linux”。怎么做?

以下是通过sftp发送文件的代码:

with pysftp.Connection(host=host, username=userName, password=passWord) as sftpVal:
    #print(sftpVal.listdir()) #list directories in sftp home
    sftpVal.put(source_file_path,'incoming/'+fileName) #(localPath, destinationPath)

1 个答案:

答案 0 :(得分:0)

一个选项是读取文件内容,根据需要更改它们,将它们保存到临时文件,然后发送临时文件。例如:

with open('file_name.txt') as original_file, open('file_to_send.txt', 'w') as send_file:  # Open the original and prepared files
    content = original_file.read()
    content = content.replace('\r\n', '\n')  # Change the line endings
    content = content.encode('utf-8')  # Encode in UTF-8
    send_file.write(content)

# Do your file send here but with the prepared file instead.

os.remove('file_to_send.txt')  # Optional removal of temp file.