from ftplib import FTP
def conn_ftp():
'''
作用:连接ftp服务器
参数:无
返回:ftp服务器连接的对象
'''
ftp_ip = "127.0.0.1"
ftp_port = 21
ftp_user = "zcz"
ftp_password = "zcz"
ftp = FTP()
ftp.connect(ftp_ip, ftp_port)
ftp.login(ftp_user, ftp_password)
print(ftp.getwelcome())
return ftp
ftp = conn_ftp()
def display_dir(ftp, path):
'''
作用:进入并展示指定的目录内容
参数1:ftp连接对象
参数2:要展示的目录
返回:无
'''
ftp.cwd(path)
print("当前所在位置为:")
print(ftp.pwd())
print("\n显示目录内容:")
print(ftp.dir())
print("\n文件和文件夹名为:")
for i in ftp.nlst():
print(i)
path = "/"
display_dir(ftp, path)
def diff_dir(ftp, path):
'''
作用:区分文件和文件夹
参数1:ftp连接对象
参数2:要展示的目录
返回:无
'''
ftp.cwd(path)
print("当前所在位置为:")
print(ftp.pwd())
print("\n显示目录内容:")
dirs = []
ftp.dir(".", dirs.append)
for i in dirs:
print(i)
if("drw" in i):
print("目录为:" + i.split(" ")[-1])
else:
print("文件为:" + i.split(" ")[-1])
path = "/"
diff_dir(ftp, path)
def get_dir_name(s):
'''
作用:需要文件或文件夹名
参数1:需要截取的字符串
返回:文件或文件夹名
'''
dir_name = ""
k = 0
record = ""
for i in s:
if(record == " " and i != " "):
k = k + 1;
if(k >= 3):
dir_name = dir_name + i;
record = i
print(dir_name)
return dir_name
get_dir_name("05-25-22 02:52PM test")
get_dir_name("05-25-22 03:32PM 89098 hello.txt")
ftp = FTP(host='127.0.0.1', user='zcz', passwd='zcz')
ftp.cwd('/test')
fd = open('D:\\ksafe\\ksoft\\scripts\\py\\test.xlsx', 'rb')
ftp.storbinary('STOR test.xlsx', fd)
fd.close()
ftp.quit()
ftp.close()
ftp = FTP(host='127.0.0.1', user='zcz', passwd='zcz')
fd = open('D:/test/test.xlsx', 'wb')
ftp.cwd('/test/')
ftp.retrbinary('RETR test.xlsx', fd.write, 2048)
fd.close()
ftp.quit()
ftp.close()