phantomxjc 发表于 2023-5-16 09:36

ftp上传和下载无格式的文件

```
from ftplib import FTP
import shutil
import os
import datetime
from ftplib import FTP
import re

def yearmonthday():
    date01 = datetime.date.today()
    date01 = str(date01)
    year = date01
    month = date01
    day = date01
    monthday = month + day
    filename = str(year) +"."+ str(month) +"."+ str(day)

    return filename

def create_file(filename):


   # 经常用到的(如果文件夹不存在,则创建该文件夹)
    if not os.path.exists("F:" + filename):
      os.makedirs("F:" + filename)
    localdir= "F:" + filename
    return localdir



def DownLoadFileTree(LocalDir, RemoteDir):

    ftp = FTP()
    # 连接ftp
    ftp.connect("", )
    #ftp.connect("", )
    # ftp登录
    ftp.login("", "")
    #ftp.login("", "")
    # 查看欢迎信息
    print(ftp.getwelcome())


    remote_folder = RemoteDir
    local_folder = LocalDir


    ftp.cwd(remote_folder)

    if not os.path.exists(local_folder):
      os.makedirs(local_folder)

    filenames = ftp.nlst()
    for filename in filenames:
      # 如果文件是空文件夹,创建一个本地空文件夹并跳过
      if ftp.size(filename) == 0 and ftp.nlst(filename) == ['.', '..']:
            os.makedirs(os.path.join(local_folder, filename), exist_ok=True)
            continue
      # 如果文件是无格式文件,读取二进制数据并保存到本地
      elif '.' not in filename:
            with open(os.path.join(local_folder, filename), 'wb') as f:
                ftp.retrbinary(f'RETR {filename}', f.write)

    ftp.quit()

def upLoadFileTree(LocalDir, RemoteDir):

    ftp = FTP()
    # 连接ftp
    ftp.connect("", )
    # ftp登录
    ftp.login("", "")
    # 查看欢迎信息
    print(ftp.getwelcome())

    ftp.mkd(RemoteDir)

    ftp.cwd(RemoteDir)
    for filename in os.listdir(LocalDir):
      local_path = os.path.join(LocalDir, filename)
      # 判断是否是无格式文件
      if '.' not in filename:
            # 将无格式文件上传到FTP服务器
            with open(local_path, 'rb') as f:
                ftp.storbinary(f'STOR {filename}', f)
            print(f'Uploaded file: {filename}')

    ftp.quit()


filename = yearmonthday()
print (filename)
#RemoteDir = ''
djbh = input("请输入登记编号:")
year = djbh
monthday = djbh
RemoteDir = 'Arch'+ year + '\\' + monthday + '\\' + djbh

localdir = create_file(filename)
localdir = localdir +'\\'+ djbh
print(localdir)
RemoteDir2 = 'Arch'+ year + '\\' + monthday + '\\' + djbh + '\\' + djbh
DownLoadFileTree(localdir, RemoteDir)
upLoadFileTree(localdir, RemoteDir2)









```

zhang7069 发表于 2023-5-16 14:09

感谢楼主分享
页: [1]
查看完整版本: ftp上传和下载无格式的文件