how to upload ziped file on server via ftp [duplicate] - python

This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 3 years ago.
i have this code in python for upload photos.zip file on the server via ftp.
import ftplib
session = ftplib.FTP('server.address.com','USERNAME','PASSWORD')
file = open('c:\archived\photos.zip','rb') # file to send
session.storbinary('STOR photos.zip', file) # send the file
file.close() # close file and FTP
session.quit()
but i have this error :
T
raceback (most recent call last):
File "a.py", line 24, in <module>
file = open('c:\archived\photos.zip','rb')
IOError: [Errno 22] invalid mode ('rb') or filename: 'c:\archived\photos.zip'

You have to escape the backslashes in the path:
file = open('c:\\archived\\photos.zip','rb')

Use os.path.join which is considered better.
file = open(os.path.join('c:/','archived','photos.zip'),'rb')
If you want to stick to your string, use \\ instead of \.

Related

"[Errno 2]" No such file or directory [duplicate]

This question already has answers here:
Trying to use open(filename, 'w' ) gives IOError: [Errno 2] No such file or directory if directory doesn't exist
(3 answers)
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 2 months ago.
This post was edited and submitted for review 2 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Traceback (most recent call last):
File "c:\Users\*\Documents\GitHub\_Testes\novo_teste.py", line 1, in <module>
teste = open('teste.txt', 'w')
^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'teste.txt'
I don't understand why it doesn't create the file and instead returns this error
I already tried 'w', 'w+', 'x', 'x+'. It simply only accepts if I use the absolute path, shouldn't it accept using the script directory as a base?
I tried using 'os.getcwd()':
import os
print(os.getcwd()) # Show the actual directory
arquivo = open(os.getcwd()+"\\teste.txt", "w")
arquivo.write('teste')
arquivo.close()
result:
PS C:\Users\*\Documents\GitHub\_Testes> & C:/Users/*/AppData/Local/Programs/Python/Python311/python.exe c:/_Projetos/_Testes/testes.py
C:\Users\*\Documents\GitHub\_Testes
Traceback (most recent call last):
File "c:\_Projetos\_Testes\testes.py", line 3, in <module>
arquivo = open(os.getcwd()+"\\teste.txt", "w")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\*\\Documents\\GitHub\\_Testes\\teste.txt'
This is because from where you're calling (python novo_teste.py) it cannot find the file where you are (check if the path exist). You probably calling this from another directory.
If you want understanding or visualize the actual directory, do this:
import os
print(os.getcwd()) # Show the actual directory
print(os.listdir()) # Show all files and folder on it
file = open("teste.txt", "w")

How do you open text files in python3? [duplicate]

This question already has answers here:
Why am I getting a FileNotFoundError? [duplicate]
(8 answers)
Closed 1 year ago.
file = open('python-ai-info.txt', 'r')
words = file.read()
file.close()
Is this correct? Please help me fix it. I want to open file named python-ai-info.txt. I am currently getting error:
Traceback (most recent call last):
File "C:\Users\sgcoder1337\AppData\Local\Programs\Python\Python38-32\rhyme ai.py", line 1, in <module>
file = open('python-ai-info.txt', 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'python-ai-info.txt'
Your code is correct, the error occurs because your directory is an invalid/nonexistent directory, try to use the complete directory like:
'C:/Users/Username/Desktop/Folder/filename.txt'
For opening file:
file = open(directory, flag)
Main flags (modes) are:
"r" for reading text, throws an exception if the file doesn't exist
"rb" for reading bytes, throws an exception if the file doesn't exist
"w" for writing text, doesn't throw an exception if the file doesn't exist, but creates it
"wb" for writing bytes, doesn't throw an exception if the file doesn't exist, but creates it
"a" for appending text, throws an exception if the file doesn't exist
"ab" for appending bytes, throws an exception if the file doesn't exist
"x" for creating files without opening, throws an exception if the file already exist
For reading files:
txt = file.read() # get the whole text
line = file.readline() # get a line
lines = file.readlines() # get a list of lines
For writing text:
file.write('txt')
For closing:
file.close()
For more detailed and complete info have a look here

How do I use ftp.storbinary to upload a file? [duplicate]

This question already has an answer here:
ftplib.error_perm: 553 Could not create file. (Python 2.4.4)
(1 answer)
Closed 2 years ago.
I am just starting to learn Python. I'm trying to upload a file as follows:
import ftplib
myurl = 'ftp.example.com'
user = 'user'
password = 'password'
myfile = '/Users/mnewman/Desktop/requested.txt'
ftp = ftplib.FTP(myurl, user, password)
ftp.encoding = "utf-8"
ftp.cwd('/public_html/')
ftp.storbinary('STOR '+myfile, open(myfile, 'rb'))
But get the following error:
Traceback (most recent call last):
File "/Users/mnewman/.spyder-py3/temp.py", line 39, in <module>
ftp.storbinary('STOR '+myfile, open(myfile, 'rb'))
File "ftplib.pyc", line 487, in storbinary
File "ftplib.pyc", line 382, in transfercmd
File "ftplib.pyc", line 348, in ntransfercmd
File "ftplib.pyc", line 275, in sendcmd
File "ftplib.pyc", line 248, in getresp
error_perm: 553 Can't open that file: No such file or directory
What does "that file" refer to and what do I need to do to fix this?
Reading the traceback, the error is deep in the ftp stack processing a response from the server. FTP server messages aren't standardized, but from the text its clear that the FTP server is unable to write the file on the remote side. This can happen for a variety of reasons - perhaps there is a permissions problem (the identity of the FTP server process does not have rights to a target), the write is outside of a sandbox setup on the server, or even that its already open in another program.
But in your case, you are using the full source file name in the "STOR" command when it wants the target path. Depending on whether you want to write subdirectories on the server, calculating the target name can get complicated. If you just want the server's current working directory, you could
ftp.storbinary(f'STOR {os.path.split(myfile)[1]}', open(myfile, 'rb'))
"That file" refers to the file that you're trying to upload to the FTP. According to your code, it refers to the line: myfile = '/Users/mnewman/Desktop/requested.txt'. You get this error because Python can't find the file in the path. Check whether it exists in the correct path. If you want to test whether there is an error in the script, you can add a test file to the directory in which your Python script exists and then run the script with the path of that file.
Example Script for FTP Upload:
import ftplib
session = ftplib.FTP('ftp.example.com','user','password')
file = open('hello.txt','rb') # file to send
session.storbinary('STOR hello.txt', file) # send the file
file.close() # close file and FTP
session.quit()

Python zipfile: file name with new line characters

Somebody managed somehow to add a new line character \r\n to the name of a file in a zip, and that makes ZipFile fail when it tries to extract the zip:
2019-07-23 14:05:12,285 - __main__ - ERROR - Error desconocido: [Errno 22] Invalid argument: 'descargados\\03_26298_19\\ANEXO\r\n.pdf'. Saliendo.
Traceback (most recent call last):
File "motor.py", line 51, in main
procesar_descarga(zip_object, ruta_temp, ruta_final)
File "C:\Users\david\pycharmProjects\descargueitor2\volcado.py", line 90, in procesar_descarga
zip_object.extractall(str(ruta_temp))
File "C:\Users\david\Anaconda3\lib\zipfile.py", line 1616, in extractall
self._extract_member(zipinfo, path, pwd)
File "C:\Users\david\Anaconda3\lib\zipfile.py", line 1670, in _extract_member
open(targetpath, "wb") as target:
OSError: [Errno 22] Invalid argument: 'descargados\\03_26298_19\\ANEXO\r\n.pdf'
I tried the same file with several programs:
The built-in compressed files reader in Windows explorer just ignores the file: it is not listed nor extracted.
WinZip lists the file, but throws an error when opening or extracting the file.
7Zip can read and extract the file: it just converts the bad characters to underscores.
Is there any way to deal with this in Python? It looks like files in a zip cannot be renamed using the library.

Python get data from named pipe

How do I read from a named pipe in Python 3.5.3?
The pipe's name and location is /tmp/shairport-sync-metadata and it can be viewed by anybody, but only modified by the shairport-sync user.
Other websites and questions say to use os.mkfifo("pipe-location") but I've been getting this error:
>>> import os
>>> os.mkfifo("/tmp/shairport-sync-metadata")
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
os.mkfifo("/tmp/shairport-sync-metadata")
FileExistsError: [Errno 17] File exists
Is there a way to get around this? Sorry for the nooby question.
os.mkfifo is used to create fifo. Use open to open/read fifo already exist:
with open('/tmp/shairport-sync-metadata') as f: # add `rb` for binary mode
# line-by-line read
for line in f:
print(line)
# f.read(1024) # to read 1024 characters

Categories