公司项目刚好有个小需求,要遍历FTP文件夹下的图片,并写进数据库,非常适合练手
从网上找了一段代码,改造了一下
中文是个大坑
#encoding=utf-8 from ftplib import FTP import os, sys, string, datetime, time, socket, pymssql import _mssql import uuid import decimal reload(sys) sys.setdefaultencoding('utf8') class MYFTP: def __init__(self, hostaddr, username, password, remotedir, port=21): self.hostaddr = hostaddr self.username = username self.password = password self.remotedir = remotedir self.port = port self.ftp = FTP() self.file_list = [] def __del__(self): self.ftp.close() def login(self): ftp = self.ftp timeout = 300 socket.setdefaulttimeout(timeout) ftp.set_pasv(True) ftp.connect(self.hostaddr, self.port) ftp.login(self.username, self.password) print u'成功登录到 %s' % (self.hostaddr) ftp.cwd(self.remotedir) def list_files(self, caseId, docCaseId, remotedir='./'): self.ftp.cwd(remotedir) print(u'正在处理目录 %s' % self.ftp.pwd()) self.file_list = [] self.ftp.dir(self.get_file_list) for item in self.file_list: sql_str.append(''' INSERT INTO XXX( OrderID, CaseID, DocCaseID, EvidenceName, Amount, Page, TotalPage, FilePath, FileName, Remark) VALUES ('%s', '%s', '%s', '%s', '1', '1', '1', '%s', '%s', '%s'); ''' % (self.file_list.index(item) + 1, caseId.encode("UTF-8"), docCaseId.encode("UTF-8"), item[1].split('.')[0], remotedir.encode("UTF-8"), item[1], "FROM FTP")) def get_file_list(self, line): ret_arr = [] file_arr = self.get_filename(line) if file_arr[1] not in ['.', '..']: self.file_list.append(file_arr) def get_filename(self, line): pos = line.rfind(':') while(line[pos] != ' '): pos += 1 while(line[pos] == ' '): pos += 1 while(line[pos] != ' '): pos += 1 while(line[pos] == ' '): pos += 1 file_arr = [line[0], line[pos:]] return file_arr if __name__ == '__main__': try: conn = pymssql.connect(host='.',user='sa',password='XXX',database='XXX',charset='utf8') cur = conn.cursor() #先获取FTP配置 cur.execute("SELECT ParamValue FROM XXX WHERE ParamName = 'FTP地址';") hostaddr = cur.fetchone()[0].encode("UTF-8") # ftp地址 cur.execute("SELECT ParamValue FROM XXX WHERE ParamName = 'FTP用户名';") username = cur.fetchone()[0].encode("UTF-8") # 用户名 cur.execute("SELECT ParamValue FROM XXX WHERE ParamName = 'FTP密码';") password = cur.fetchone()[0].encode("UTF-8") # 密码 cur.execute("SELECT ParamValue FROM XXX WHERE ParamName = 'FTP端口';") port = cur.fetchone()[0].encode("UTF-8") # 端口号 #测试用 # hostaddr = "XXX" # ftp地址 # username = "XXX" # 用户名 # password = "XXX" # 密码 # port = 21 # 端口号 #连接FTP rootdir_remote = '' # 远程目录 f = MYFTP(hostaddr, username, password, rootdir_remote, port) f.login() sql_str = [] cur.execute(''' USE XXX SELECT 'A'+ CONVERT(VARCHAR(50),hr.Id) CaseID, CONVERT(VARCHAR(50),hr.Id) DocCaseID, '/' + REPLACE(FilePath, '\','/') FilePath FROM XXX f JOIN XXX hr ON hr.BussinessTypeID = f.BussinessTypeId AND hr.BussinessId = f.BussinessId WHERE FilePath IS NOT NULL AND FilePath <> ''AND f.BussinessTypeId IN (1,2,3,5) AND NOT EXISTS(SELECT * FROM XXX h WHERE h.BussinessTypeId = f.BussinessTypeId AND h.BussinessId = f.BussinessId) AND FilePath LIKE '%Owner%' ''') rows = cur.fetchall() for row in rows: f.list_files(row[0], row[1], row[2].replace("//","/")) #拼好的字符串一次性执行,如果update/delete/insert记得要conn.commit(),否则数据库事务无法提交 #print(''.join(sql_str)) #直接执行的话,其中有中文会报错,先输出到文本再手动执行了 #cur.execute(''.join(sql_str)) #conn.commit() f = file('result.sql','a+') f.writelines(''.join(sql_str)) f.close() #关闭数据库连接 cur.close() conn.close() except Exception as ex: print(ex)
小结一下:
1、语法不熟的话,第一次谈不上效率,每写一句都要查。。。各种报错各种问题,如果用C#控制台可能早就处理完了
2、中文是个坑
3、打包成exe又是个坑
4、代码看着比较舒畅,但语法不熟,随便一个函数都要靠查和试
5、就一个py文件比较干脆,又能处理FTP又能处理SQL,还能读写文件
6、尝试一下可以,日常任务可能用不上,C#照样可以处理。可能侧重点不同,Python可能在处理爬虫、图形方面比较强悍