Search code examples
pythonpathsftpparamiko

Python paramiko get command path syntax


I am looking to download files from an sFTP server to my local computer and would like to specify where the files go as they download.

I've successfully connected to an sFTP server using this code:

import paramiko

#SET UP A CLIENT
ssh = paramiko.SSHClient()

#AUTO ADD HOST KEY
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

#CONNECT TO SFTP
ssh.connect(server, port=port, username=usereu, password=passeu)

#OPEN SFTP
sftp = ssh.open_sftp()

But now am attempting to get a file and direct it to this path: 'C:\Users\Me\Documents\Python Scripts\Test Folder'

However, this code fails:

sftp.get('file1.csv', 'C:\Users\Me\Documents\Python Scripts\Test Folder\file1.csv')

Response is: '(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape'

I think there is an issue of syntax in my path, but have been unable to troubleshoot this after researching.


Solution

  • to use a path in Windows you'll need to escape it properly; either with double slashes

    'C:\\Users\\Me\\Documents\\Python Scripts\\Test Folder\\file1.csv'
    

    or by using a type of string that the python interpreter can understand - an r string, also known as a raw string, like so

    r'C:\Users\Me\Documents\Python Scripts\Test Folder\file1.csv'