前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 上传所有文件到FTP服务器 脚本

python 上传所有文件到FTP服务器 脚本

作者头像
用户5760343
发布2022-05-13 09:51:38
1.9K0
发布2022-05-13 09:51:38
举报
文章被收录于专栏:sktjsktj

!/bin/env python

import os, sys, ftplib from getpass import getpass from mimetypes import guess_type

nonpassive = False # passive FTP by default remotesite = 'learning-python.com' # upload to this site remotedir = 'books' # from machine running on remoteuser = 'lutz' remotepass = getpass('Password for %s on %s: ' % (remoteuser, remotesite)) localdir = (len(sys.argv) > 1 and sys.argv[1]) or '.' cleanall = input('Clean remote directory first? ')[:1] in ['y', 'Y']

print('connecting...') connection = ftplib.FTP(remotesite) # connect to FTP site connection.login(remoteuser, remotepass) # log in as user/password connection.cwd(remotedir) # cd to directory to copy if nonpassive: # force active mode FTP connection.set_pasv(False) # most servers do passive

if cleanall: for remotename in connection.nlst(): # try to delete all remotes try: # first, to remove old files print('deleting remote', remotename) connection.delete(remotename) # skips . and .. if attempted except: print('cannot delete remote', remotename)

count = 0 # upload all local files localfiles = os.listdir(localdir) # listdir() strips dir path # any failure ends script for localname in localfiles: mimetype, encoding = guess_type(localname) # e.g., ('text/plain', 'gzip') mimetype = mimetype or '?/?' # may be (None, None) maintype = mimetype.split('/')[0] # .jpg ('image/jpeg', None')

代码语言:javascript
复制
localpath = os.path.join(localdir, localname)
print('uploading', localpath, 'to', localname, end=' ')
print('as', maintype, encoding or '')

if maintype == 'text' and encoding == None:
    # use ascii mode xfer and bytes file
    # need rb mode for ftplib's crlf logic
    localfile = open(localpath, 'rb')
    connection.storlines('STOR ' + localname, localfile)

else:
    # use binary mode xfer and bytes file
    localfile = open(localpath, 'rb')
    connection.storbinary('STOR ' + localname, localfile)

localfile.close()
count += 1

connection.quit() print('Done:', count, 'files uploaded.')

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-05-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • !/bin/env python
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档