简体   繁体   中英

To copy the files from a server to a local directory using python

I'm trying to write the copied files from the server to a local directory.But finding permission denied to access the folder.....I present my code here.Please correct my mistake....

Code:

from ftplib import FTP
import os
ip="ip address"
password='pwd'

ftp=FTP(ip)
ftp.login(username,password)
print "File List:"
files=ftp.dir()
mypath='C:\\test\\'+files
os.makedirs(mypath)
for filek in files: # Loop - looking for matching files
    file = open("%s" %(mypath), 'w')
    ftp.retrbinary('RETR '+ filek, file.write)

i'm getting the following error:

IOError: [Errno 13] Permission denied: 'C:\\test\\November'

You create directories with os.makedirs(mypath) which you later want to write to as a file in file = open("%s" %(mypath), 'w') .

Either you edit mypath='C:\\\\test\\\\'+files to mypath='C:\\\\test\\\\' and then

for filek in files: # Loop - looking for matching files
    f = open("%s/%s" % (mypath, filek), 'w') # the slash will also work in windows!
    ftp.retrbinary('RETR '+ filek, file.write)
    f.close()

or you have to introduce filenames within your loop.

You also have to handle the case where os.makedirs(mypath) fails because the directory at mypath already exists. And please don't use file as variable name, it overwrites the builtin file .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM