我们有一个ftp文件夹,其中包含700多个文件(generetad由我们的系统自动生成)文件名如:ff9a6c2b-4222-4464-a314-dce56efe76cb.txt
..ffbaef37-9d73-41d5-8f23-7ca7c82b3969.txt
..fffa92f0-9e76-4cce-8933-d256bac90ffa.txt
我正在尝试编写一个脚本来自动下载文件,并防止多次下载文件,我的想法是将所有下载的文件名存储在xml文件中(效果很好),并在下载前检查该名称是否存在于xml文件中。
问题是即使有8个新文件,它也只能下载一个。
我的代码
import ftputil
from subprocess import Popen
import ftplib
import os
import os.path
import xml.etree.cElementTree as ET
server = 'ip_adress'
user = 'user'
password = 'Passwd'
ftp = ftplib.FTP(server)
ftp.login(user, password)
files = []
root = ET.Element("files")
file_exists = os.path.isfile("filename.xml")
if file_exists:
f = ET.parse("filename-Copie.xml")
root = f.getroot()
files = ftp.nlst()
for file in files:
for item in root:
if file != item.text :
#print ("the file name: ",item.text, " already exist")
ftp_host = ftputil.FTPHost(server, user, password)
ftp_host.download(file, file)
ET.SubElement(root, "file", name="filename").text = file
tree = ET.ElementTree(root)
tree.write("filename.xml")
p = Popen("move.bat", cwd=r"C:\\Users\\Sas\\Desktop\\ftpdown\\")
stdout, stderr = p.communicate()
print("Finished!")
else:
f = open("filename.xml", "w")
with ftputil.FTPHost(server, user, password) as ftp_host:
files = ftp_host.listdir(ftp_host.curdir)
root = ET.Element("files")
for file in files:
if ftp_host.path.isfile(file):
ftp_host.download(file, file)
ET.SubElement(root, "file", name="filename").text = file
tree = ET.ElementTree(root)
tree.write("filename.xml")
p = Popen("move.bat", cwd=r"C:\\Users\\Sas\\Desktop\\ftpdown\\")
stdout, stderr = p.communicate()
print("Finished!")
我通过将从xml提取的文件名存储到列表中解决了问题这是下面的代码,如果有人和我有同样的问题]
import ftputil
from subprocess import Popen
import ftplib
import os
import os.path
import xml.etree.cElementTree as ET
server = 'ip-adress'
user = 'user'
password = 'Passwd'
ftp = ftplib.FTP(server)
ftp.login(user, password)
files = []
root = ET.Element("files")
file_exists = os.path.isfile("filename.xml")
if file_exists:
f = ET.parse("filename-Copie.xml")
root = f.getroot()
files = ftp.nlst()
oldfile = []
for child in root:
oldfile.append(child.text)
for file in files:
if file not in oldfile:
ftp_host = ftputil.FTPHost(server, user, password)
ftp_host.download(file, file)
ET.SubElement(root, "file", name="filename").text = file
tree = ET.ElementTree(root)
tree.write("filename.xml")
p = Popen("move.bat", cwd=r"C:\\Users\\Sas\\Desktop\\ftpdown\\")
stdout, stderr = p.communicate()
print("Finished!")
else:
f = open("filename.xml", "w")
with ftputil.FTPHost(server, user, password) as ftp_host:
files = ftp_host.listdir(ftp_host.curdir)
root = ET.Element("files")
for file in files:
if ftp_host.path.isfile(file):
ftp_host.download(file, file)
ET.SubElement(root, "file", name="filename").text = file
tree = ET.ElementTree(root)
tree.write("filename.xml")
p = Popen("move.bat", cwd=r"C:\\Users\\Sas\\Desktop\\ftpdown\\")
stdout, stderr = p.communicate()
print("Finished!")