Paramiko 下载、处理并重新上传同一文件
Paramiko Download, process and re-upload the same file
我正在使用 Paramiko 创建 SFTP 客户端来创建 JSON 文件的备份副本,读取原始文件的内容,然后更新(原始文件)。我能够让这段代码工作:
# open sftp connection stuff
# read in json create backup copy - but have to 'open' twice
read_file = sftp_client.open(file_path)
settings = json.load(read_file)
read_file = sftp_client.open(file_path)
sftp_client.putfo(read_file, backup_path)
# json stuff and updating
new_settings = json.dumps(settings, indent=4, sort_keys = True)
# update remote json file
with sftp_client.open(file_path, 'w') as f:
f.write(new_settings)
然而,当我尝试清理代码并结合备份文件创建和 JSON 加载时:
with sftp_client.open(file_path) as f:
sftp_client.putfo(f, backup_path)
settings = json.load(f)
将创建备份文件,但json.load
将因没有任何内容而失败。如果我颠倒顺序,json.load
将读入值,但备份副本将为空。
我在 Windows 机器上使用 Python 2.7,创建到 QNX (Linux) 机器的远程连接。感谢任何帮助。
提前致谢。
如果你想第二次读取文件,你必须寻找文件读指针回到文件开头:
with sftp_client.open(file_path) as f:
sftp_client.putfo(f, backup_path)
f.seek(0, 0)
settings = json.load(f)
尽管这在功能上等同于带有两个 open
的原始代码。
如果您的目标是优化代码,以避免下载文件两次,您将不得不 read/cache 将文件存入内存,然后从缓存中上传和加载内容。
f = BytesIO()
sftp_client.getfo(file_path, f)
f.seek(0, 0)
sftp_client.putfo(f, backup_path)
f.seek(0, 0)
settings = json.load(f)
我正在使用 Paramiko 创建 SFTP 客户端来创建 JSON 文件的备份副本,读取原始文件的内容,然后更新(原始文件)。我能够让这段代码工作:
# open sftp connection stuff
# read in json create backup copy - but have to 'open' twice
read_file = sftp_client.open(file_path)
settings = json.load(read_file)
read_file = sftp_client.open(file_path)
sftp_client.putfo(read_file, backup_path)
# json stuff and updating
new_settings = json.dumps(settings, indent=4, sort_keys = True)
# update remote json file
with sftp_client.open(file_path, 'w') as f:
f.write(new_settings)
然而,当我尝试清理代码并结合备份文件创建和 JSON 加载时:
with sftp_client.open(file_path) as f:
sftp_client.putfo(f, backup_path)
settings = json.load(f)
将创建备份文件,但json.load
将因没有任何内容而失败。如果我颠倒顺序,json.load
将读入值,但备份副本将为空。
我在 Windows 机器上使用 Python 2.7,创建到 QNX (Linux) 机器的远程连接。感谢任何帮助。
提前致谢。
如果你想第二次读取文件,你必须寻找文件读指针回到文件开头:
with sftp_client.open(file_path) as f:
sftp_client.putfo(f, backup_path)
f.seek(0, 0)
settings = json.load(f)
尽管这在功能上等同于带有两个 open
的原始代码。
如果您的目标是优化代码,以避免下载文件两次,您将不得不 read/cache 将文件存入内存,然后从缓存中上传和加载内容。
f = BytesIO()
sftp_client.getfo(file_path, f)
f.seek(0, 0)
sftp_client.putfo(f, backup_path)
f.seek(0, 0)
settings = json.load(f)