I am trying to upload file from windows server to a unix server (basically trying to do FTP). I have used the code below
#!/usr/bin/python
import ftplib
import os
filename = "MyFile.py"
ftp = ftplib.FTP("xx.xx.xx.xx")
ftp.login("UID", "PSW")
ftp.cwd("/Unix/Folder/where/I/want/to/put/file")
os.chdir(r"\\windows\folder\which\has\file")
ftp.storbinary('RETR %s' % filename, open(filename, 'w').write)
I am getting the following error:
Traceback (most recent call last):
File "Windows\folder\which\has\file\MyFile.py", line 11, in <module>
ftp.storbinary('RETR %s' % filename, open(filename, 'w').write)
File "windows\folder\Python\lib\ftplib.py", line 466, in storbinary
buf = fp.read(blocksize)
AttributeError: 'builtin_function_or_method' object has no attribute 'read'
Also all contents of MyFile.py got deleted .
Can anyone advise what is going wrong.I have read that ftp.storbinary is used for uploading files using FTP.
If you are trying to store a non-binary file (like a text file) try setting it to read mode instead of write mode.
ftp.storlines("STOR " + filename, open(filename, 'rb'))
for a binary file (anything that cannot be opened in a text editor) open your file in read-binary mode
ftp.storbinary("STOR " + filename, open(filename, 'rb'))
also if you plan on using the ftp lib you should probably go through a tutorial, I'd recommend this article from effbot.
Combined both suggestions. Final answer being
#!/usr/bin/python
import ftplib
import os
filename = "MyFile.py"
ftp = ftplib.FTP("xx.xx.xx.xx")
ftp.login("UID", "PSW")
ftp.cwd("/Unix/Folder/where/I/want/to/put/file")
os.chdir(r"\\windows\folder\which\has\file")
myfile = open(filename, 'r')
ftp.storlines('STOR ' + filename, myfile)
myfile.close()
try making the file an object, so you can close it at the end of the operaton.
myfile = open(filename, 'w')
ftp.storbinary('RETR %s' % filename, myfile.write)
and at the end of the transfer
myfile.close()
this might not solve the problem, but it may help.
ftplib supports the use of context managers so you can make it even simpler as such
with ftplib.FTP('ftp_address', 'user', 'pwd') as ftp, open(file_path, 'rb') as file:
ftp.storbinary(f'STOR {file_path.name}', file)
...
This way you are robust against both file and ftp issues without having to insert try/except/finally blocks. And well, it's pythonic.
PS: since it uses f-strings is python >= 3.6 only but can easily be modified to use the old .format() syntax
Related
I'm trying to create a .txt file with some data, and I want the file name to be the current time. But when I run my code it creates an empty file instead, without any file-type. Here is the code in question:
filename = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d_%H:%M')
with open('%s.txt' % filename, 'w') as open_file:
# writing to file
It seems to ignore the ".txt" part because if i write the code like this it works just fine:
with open('filename.txt', 'w') as open_file:
It runs fine on my machine (Ubuntu 16.04 and python 3.5)
import datetime
import time
filename = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d_%H:%M')
with open('%s.txt' % filename, 'w') as file:
file.write('code written')
please provide more info
And yes i am getting .txt in my file name
In windows, you cant use : in the filename. It stops the creation of the file when it reaches the colon.
I need to read a local file and copy to remote location with FTP, I copy same file file.txt to remote location repeatedly hundreds of times with different names like f1.txt, f2.txt... f1000.txt etc. Now, is it necessary to always open, read, close my local file.txt for every single FTP copy or is there a way to store into a variable and use that all time and avoid file open, close functions. file.txt is small file of 6KB. Below is the code I am using
for i in range(1,101):
fname = 'file'+ str(i) +'.txt'
fp = open('file.txt', 'rb')
ftp.storbinary('STOR ' + fname, fp)
fp.close()
I tried reading into a string variable and replace fp but ftp.storbinary requires second argument to have method read(), please suggest if there is better way to avoid file open close or let me know if it has no performance improvement at all. I am using python 2.7.10 on Windows 7.
Simply open it before the loop, and close it after:
fp = open('file.txt', 'rb')
for i in range(1,101):
fname = 'file'+ str(i) +'.txt'
fp.seek(0)
ftp.storbinary('STOR ' + fname, fp)
fp.close()
Update Make sure you add fp.seek(0) before the call to ftp.storbinary, otherwise the read call will exhaust the file in the first iteration as noted by #eryksun.
Update 2 depending on the size of the file it will probably be faster to use BytesIO. This way the file content is saved in memory but will still be a file-like object (ie it will have a read method).
from io import BytesIO
with open('file.txt', 'rb') as f:
output = BytesIO()
output.write(f.read())
for i in range(1, 101):
fname = 'file' + str(i) + '.txt'
output.seek(0)
ftp.storbinary('STOR ' + fname, fp)
I'm trying to upload a file using ftplib in Python.
ftp = FTP('...')
ftp.login('user', 'pass')
f = open(filename)
ftp.storbinary(filename, f)
f.close()
ftp.quit()
storbinary is returning error_perm: 500 Unknown command., which is strange since I'm following its specification. Google search returns very little information. Anyone encountered this problem ?
It looks like you're using storbinary incorrectly. You want to pass "STOR filename-at-location", f) to send the file. Does this work?
ftp = FTP('...')
ftp.login('user', 'pass')
with open(filename) as contents:
ftp.storbinary('STOR %s' % filename, contents)
ftp.quit()
I am using the following code to upload a SQLITE3 Database file. For some reason, the script does not completely upload the file (the uploaded filesize is less than the original)
FTP = ftplib.FTP('HOST','USERNAME','PASSWORD')
FTP.cwd('/public_html/')
FILE = 'Database.db';
FTP.storbinary("STOR " + FILE, open(FILE, 'r'))
FTP.quit()
When I go to open the uploaded file in SQLite Browser, it says it is an invalid file.
What am I doing incorrectly?
In the open() call, you need to specify that the file is a binary file, like so:
FTP.storbinary("STOR " + FILE, open(FILE, 'rb'))
I want to overwrite an existing file "test.txt" on my ftp server with this code:
from ftplib import FTP
HOST = 'host.com'
FTP_NAME = 'username'
FTP_PASS = 'password'
ftp = FTP(HOST)
ftp.login(FTP_NAME, FTP_PASS)
file = open('test.txt', 'r')
ftp.storlines('STOR test.txt', file)
ftp.quit()
file.close()
I don't get any error messages and the file test.txt has NOT been overwritten (the old test.txt is still on the server). I thought STOR overwrites files... Can somebody please help?
Thanks!
nvm, it's my fault...
I forgot to change the current working directory to /public_html
thanks anyway!
I think you need to open the file in write mode
file = open('test.txt', 'w')