开发者

uploading empty file to ftp with psuedo-file

开发者 https://www.devze.com 2023-01-16 05:01 出处:网络
As far as i know it is impossible to create an empty file with ftp, you have to create an empty file on the local drive, upload it, then delete it when you are done. I was wondering if it is possible

As far as i know it is impossible to create an empty file with ftp, you have to create an empty file on the local drive, upload it, then delete it when you are done. I was wondering if it is possible to do something like:

class FakeFile:
    def read(self):
        ret开发者_如何学JAVAurn '\x04'

ftpinstance.storbinary('stor fe', FakeFile())

I thought this might work because the docs for storbinary say that it takes an object with a method 'read' and calls it til it returns EOF, and \x04 is the ASCII EOF character. I have tried this though, and the file ends up on the server being a random number of kilobytes large. Am I misunderstanding something?


No need to implement your own file-like class, just use the in-memory files from builtin module StringIO (or BytesIO in Python 3):

import ftplib
import cStringIO

ftp = ftplib.FTP('ftp.example.com')
ftp.login('user', 'pass')

voidfile = cStringIO.StringIO('')
ftp.storbinary('STOR emptyfile.foo', voidfile)

ftp.close()
voidfile.close()


End of File is not ASCII 4 in modern usage. That is obsolete usage from the days of XMODEM and teletype. Try this:

class FakeFile:
    def read(self, size=0):
        return ''

since an empty read is EOF.

With your current code, you should be getting a random length file consisting entirely of '\x04' characters. This is because it seems to always have data when read. ^_-


Actually the doc reads 'reads until EOF'. I solved this by making the read function return an empty string.

0

精彩评论

暂无评论...
验证码 换一张
取 消