Skip to main content
 首页 » 编程设计

python之使用 Pysftp 从 Windows 传输文件时文件夹名称错误

2025年04月02日9tuyile006

我正在使用 Pysftp 将文件从 Windows 服务器传输到 Buffalo Terastation。我希望能够告诉它使用 PUT_R 命令传输文件夹中的所有文件,但是当我运行我的代码时,文件传输很奇怪。

我的代码:

srv.put_r('c:/temp1/photos', 'array1/test_sftp/photos', preserve_mtime=True) 

当我运行代码时,我在 Terastation 上得到的文件名看起来像

photos\.\image1.jpg 
photos\.\image2.jpg 

我猜代码没有正确处理平台之间的路径。如何更正路径?

我试过了

dest = dest.replace('\\.\\','/') 

但是我得到一个“没有这样的文件”的错误

请您参考如下方法:

我为这个问题创建了一个 hacky 解决方法。它不是很聪明,在所有情况下都可能不稳定。因此,请小心使用。使用 pysftp 0.2.9 在 Python 3.x 上测试。

import os 
import pysftp 
 
# copy all folders (non-recursively) from from_dir (windows file system) to to_dir (linux file system) 
def copy_files(host, user, pw, from_dir, to_dir): 
    cnopts = pysftp.CnOpts() 
    cnopts.hostkeys = None 
    with pysftp.Connection(host=host, username=user, password=pw, cnopts=cnopts) as sftp: 
        from_dir = os.path.normpath(from_dir) 
        to_dir = "/" + os.path.normpath(to_dir).replace("\\", "/").strip("/") 
        top_folder = os.path.split(to_dir)[1] 
        files = [file for file in os.listdir(from_dir) if os.path.isfile(os.path.join(from_dir, file))] 
        for file in files: 
            sftp.cwd(to_dir) 
            sftp.put(os.path.join(from_dir, file), os.path.join("./{}".format(top_folder), file)) 
            sftp.execute(r'mv "{2}/{0}\{1}" "{2}/{1}"'.format(top_folder, file, to_dir)) 
 
# usage: always use full paths for all directories 
copy_files("hostname", "username", "password", "D:/Folder/from_folder", "/root/Documents/to_folder")