英文:
python: pysftp only download first 10MB and exit
问题
我正在使用pysftp从服务器下载文件。
我正在调试我的代码。为此,我想要pysftp只下载10MB然后退出。
sftp_folder_location = 'outbound'
sftp = pysftp.Connection(host=主机名, username=用户名, password=密码, cnopts=cnopts)
with sftp.cd(sftp_folder_location):
local_path = '/home/ubuntu/data'
sftp.isfile(文件名)
sftp.get(文件名, os.path.join(local_path, 文件名))
sftp.close()
请注意,我已将主机名、用户名和密码部分保留为原文。
英文:
I am using pysftp to download files from server.
I am debugging my code. For that purpose i want pysftp to download only 10MB and exit.
sftp_folder_location = 'outbound'
sftp = pysftp.Connection(host=Hostname, username=Username, password=Password,cnopts=cnopts)
with sftp.cd(sftp_folder_location):
local_path = '/home/ubuntu/data'
sftp.isfile(filename)
sftp.get(filename,os.path.join(local_path, filename))
sftp.close()
答案1
得分: 1
为了将文件下载大小限制在10MB以内,您可以使用pysftp.Connection
对象的getfo
方法,结合urllib.request.urlopen
来打开文件,并仅读取前10MB的数据。以下是示例代码:
import urllib.request
sftp_folder_location = 'outbound'
sftp = pysftp.Connection(host=Hostname, username=Username, password=Password, cnopts=cnopts)
with sftp.cd(sftp_folder_location):
filename = 'example.txt'
remote_path = sftp.normalize('example.txt')
local_path = '/home/ubuntu/data'
with sftp.open(remote_path, 'r') as remote_file:
with open(os.path.join(local_path, filename), 'wb') as local_file:
data = remote_file.read(1024*1024*10) # 仅读取前10MB的数据
local_file.write(data)
sftp.close()
在这个示例中,使用sftp.open
方法打开远程文件以进行读取,然后在生成的文件对象上调用read
方法,并传入1024*1024*10
作为参数,以仅读取前10MB
的数据。with
语句用于确保在下载完成后正确关闭远程和本地文件。
英文:
To limit the file download size to 10MB, you can use the getfo method of the pysftp.Connection object along with urllib.request.urlopen to open the file and read only the first 10MB of data. Here's an example code:
import urllib.request
sftp_folder_location = 'outbound'
sftp = pysftp.Connection(host=Hostname, username=Username, password=Password, cnopts=cnopts)
with sftp.cd(sftp_folder_location):
filename = 'example.txt'
remote_path = sftp.normalize('example.txt')
local_path = '/home/ubuntu/data'
with sftp.open(remote_path, 'r') as remote_file:
with open(os.path.join(local_path, filename), 'wb') as local_file:
data = remote_file.read(1024*1024*10) # read only 10MB of data
local_file.write(data)
sftp.close()
In this example, the sftp.open
method is used to open the remote file for reading, and then the read
method is called on the resulting file object with an argument of 1024*1024*10
to read only the first 10MB
of data. The with
statement is used to ensure that both the remote and local files are properly closed after the download is complete.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论