简体   繁体   English

Python ftplib在将文件上传到FTP服务器的过程中向txt文件添加新行

[英]Python ftplib add new line to txt file during upload file to FTP server

I use following code to upload txt files in ASCII mode to FTP server 我使用以下代码将ASCII模式的txt文件上传到FTP服务器

import glob
import os
import hashlib
from ftplib import FTP 

server = '1.1.1.1'
login = 'user'
password = 'password'
path = './test_files/'
file_mask = '*.txt'

def upload_to_ftp(srv, uname, pwd, file_name):
    ftp = FTP(srv, uname, pwd)    
    ftp.cwd('Pava')    
    file = open(path+file_name, 'rb')
    ftp.storlines('STOR '+file_name, file)
    size = ftp.size(file_name)           
    ftp.close()
    file.close()
    print (size)

def local_size_check(file_name):
    file_size = os.stat(path+file_name)
    print (file_size.st_size)


file_to_upload = glob.glob1(path, file_mask)
for i in file_to_upload:
    try:
        os.rename(path+i, path+i)
    except OSError as e:
        print ('Access-error on file ' + i + ' ! \n' + str(e))
    else:
        upload_to_ftp(server, login, password, i)
        local_size_check(i)

The output of this two functions is: 78 76 Then i have dowloaded file from ftp and found that during transfering by FTP was added new line at the end of file. 这两个函数的输出是:78 76然后,我从ftp下载了文件,发现通过FTP传输期间在文件末尾添加了新行。 local and remote file screens 本地和远程文件屏幕

在此处输入图片说明

Please help to solve this problem. 请帮助解决此问题。 BTW if use binary mode new line do not add 顺便说一句,如果使用二进制模式换行不添加

You should upload your file in binary mode so that it will not be subject to the server's text interpretation. 您应该以二进制模式上传文件,这样它就不会受到服务器文本解释的约束。

Change: 更改:

ftp.storlines('STOR '+file_name, file)

to: 至:

ftp.storbinary('STOR '+file_name, file)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM