我正在使用 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
的原始代码。
如果您的目标是优化代码,为了避免两次下载文件,您必须将文件读取/缓存到内存中,然后上传并加载缓存中的内容。
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)
关于python - Paramiko 下载、处理并重新上传同一文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53252210/