问题描述
我已经在开发中成功运行了该脚本,但是在生产中,文件结构略有不同,并且出现了'FileNotFoundError:Errno 2 error No such file'错误代码。
当我使用root登录名时,我相信我会进入以下目录:
/root
我需要工作的目录是:
/BackupStorage/Test/Here
我相信我收到了错误消息,因为我的会话正试图从/root
目录运行。如何将目录更改为/BackupStorage/Test/Here
?还是我完全错了?
local_path = r'C:\Data\Scripts\Trial\Test\Here'
remote_path = f'/BackupStorage/Test/Here'
hostname = 'hostname1'
password = 'password123'
username = 'root'
port = 22
print(f'Connecting to {hostname} ...')
session = paramiko.Transport((hostname,22))
session.connect(username=username,password=password)
sftp = paramiko.SFTPClient.from_transport(session)
print(f'Connected to {hostname} - Remote Session Opened')
latest_time = -1
latest = None
# Below for loop finds latest sub-directory
for file_attr in sftp.listdir_attr(path=remote_path):
if stat.S_ISDIR(file_attr.st_mode) and file_attr.st_mtime > latest_time:
latest_time = file_attr.st_mtime
latest = file_attr.filename
# Below for loop finds the .zip file within latest sub-directory
for file_attr in sftp.listdir_attr(path=f'{remote_path}/{latest}'):
if file_attr.filename.endswith('.zip'):
sftp.get(
f'{remote_path}/{latest}/{file_attr.filename}',f'{local_path}\{file_attr.filename}'
)
print(f'Most recent {branch_name} file successfully retrieved.')
session.close
print('Remote Session Closed.')
非常感谢您的帮助。
解决方法
使用SFTPClient.chdir
:
sftp.chdir(path)
或者简单地使用绝对路径或通过其他方法校正房屋的相对路径。
,我花了很多时间研究这个问题,而我做错了所有事情,就是将一个元组缩减为一个对象,之后没有逗号。这意味着当我遍历一个我认为是元组的代码时,我的代码遍历了一个字符串-导致目标路径不完整。感谢大家的答复。