FTP question

having some trouble getting the python ftp code to work. trying to retrieve a file and getting an error on this line:

s=ftp.retrbinary(‘RETR Test.txt’, open(‘C:\Documents and Settings\cannin\Desktop\Test.txt’,‘wb’).write)

In my app I need to:

#1 edit a text file - write a part number into the text file that is on another drive
#2 trasfer a program file from the HMI computer to the other drive
#3 save the file from the other drive back to the HMI computer
#4 delete the file from the other drive

Can anyone help me with python ftp code examples for these 4 scenarios?

Thank you very much.

Here’s what I’ve got working for retreiving and sending a text file, with basic FTP error trapping.

This code gets a text file and reads it into a string buffer r:

from StringIO import StringIO
from ftplib import FTP
try:
	ftp = FTP('ComputerName')
	ftp.login()
	r = StringIO()
	ftp.retrlines('RETR FileName.txt', r.write)
except ftplib.all_errors, e:   
	errorcode_string = str(e).split(None, 1) 
	print "FTP error:"
	print errorcode_string

For sending a text file via FTP, I first create a temp file and then send it:

from ftplib import FTP
import system
filename = system.file.getTempFile(".txt") 
system.file.writeFile(filename, DataForFile) 
try :
	f = open(filename)
	ftp = FTP('ComputerName')
	ftp.login()
	ftp.storlines("STOR FileName.txt",f)
	ftp.close
except ftplib.all_errors, e:   
	errorcode_string = str(e).split(None, 1) 
	print "FTP error:"
	print errorcode_string

I hope this helps. Good luck!

thank you that put me on the right track.

this is what i have so far - Is there a way to retrieve a file defined indirectly, as you can see in the code below I was trying to compile “test.txt” and retrieve it but get file not found as its trying to find a file called “d”

thank you.

import os
import system
from ftplib import FTP

ftp = FTP(‘127.0.0.1’)
ftp.login(’’)

a = “te”
b = “st”
c = “.txt”

d = a+b+c

s=ftp.retrbinary(‘RETR “d”’, open(‘C:\Documents and Settings\cannin\Desktop\test2.txt’,‘wb’).write)
print s
ftp.close()

String substitution will allow you to refer to a variable:

s=ftp.retrbinary('RETR %s' % d, open('C:\\Documents and Settings\\cannin\\Desktop\\test2.txt','wb').write)

perfect, thank you. one other question, I havnt been able to find anything on editing a text file. Is it possible to delete or write text into a text file through ignition? for example I need to delete a 5 digit number from a text file and then write a different 5 digit number into the file. thank you.

You can bring in the text file as a string using system.file.readFileAsString, use python’s string.replace function to replace the number with a new number, and then write back to the file using system.file.writeFile:

path = "C:\\Path\\To\\File.txt" contents = system.file.readFileAsString(path) contents = contents.replace("00000","11111") system.file.writeFile(path, contents)

thank you very much!