首页 > 解决方案 > Python Paramiko SFTP 打开文件从 N 行开始

问题描述

因为我在服务器中的文件很大,为了节省从服务器下载文件的时间,所以我使用 paramikosftp.open(file)来读取服务器中的文件。

有什么方法可以让我们从文件的任何行使用sftp.open(file)或其他方式开始读取文件?


这就是我过去从本地目录读取文件的方式

# open the file and start reading from the nth line
for line in itertools.islice(file, no_line, None):
    print(line)

这就是我从服务器读取文件的方式

ssh = paramiko.SSHClient()
ssh.connect(host, port, username, password)
readfile = ssh.open_sftp()
file = readfile.open(os.path.join(path, file))
for line in file:
    print(line)

标签: pythonpython-3.xsftpparamiko

解决方案


SFTP 中没有允许您跳到第 N 行的 API。

SFTPFile.seek您可以使用方法从第 N 个字节开始读取:

file = readfile.open(os.path.join(path, file))
file.seek(offset)
for line in file:
    print(line)

推荐阅读