批量下载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("" + filename):
os.makedirs("" + filename)
localdir= "" + 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()
text = ''
line_text = ''
print("请输入")
while True:
line_text = input()
if line_text == '':
break
text += line_text + '\n'
text = text.split()
filename = yearmonthday()
#print (filename)
for i in text:
year = i
monthday = i
RemoteDir = '' + i
localdir = create_file(filename)
localdir = localdir +'\\'+i
DownLoadFileTree(localdir, RemoteDir)
print(localdir)
print(RemoteDir)
#upLoadFileTree(localdir, RemoteDir2)
```
>
‘’ 感谢感谢~ 感谢大佬分享,学习了!
页:
[1]