Question

I have made a program, and there is a function where it gets a text file called news_2014.txt from a ftp server. I currently have this code:

def getnews():
server = 'my ftp server ip'
ftp= ftplib.FTP(server)
username = 'news2'
password = ' '
ftp.login(username,password)
filename = 'ftp://my ftp server ip/news/news_2014.txt'
path = 'news'
ftp.cwd(path)
ftp.retrlines('RETR' + filename, open(filename, "w").open)

I wanna make so the program displays the lines using readlines onto a Tkinter label. But if I try calling the top function, it says:

IOError: [Errno 22] invalid mode ('w') or filename: 'ftp://news/news_2014.txt'
Was it helpful?

Solution

RETR wants just the remote path name, not a URL. Similarly, you cannot open a URL; you need to pass it a valid local filename.

Changing it to filename = 'news_2014.txt' should fix this problem trivially.

The retrlines method retrieves the lines and optionally performs a callback. You have specified a callback to open a local file for writing, but that's hardly something you want to do for each retrieved line. Try this instead:

textlines = []
ftp.retrlines('RETR ' + filename, textlines.append)

then display the contents of textlines. (Notice the space between the RETR command and its argument, too.)

I would argue that the example in the documentation is confusing for a newcomer. Someone should file a bug report.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top