循环中的python ftplib storbinary写入空文件

问题描述 投票:0回答:1

对于计划的压力测试,我尝试使用文件名递增的循环将相同的文件写入 ftp 服务器。 它工作正常,但仅适用于第一个文件。 所有其他都已创建,但都是空的。

这是我的代码:

from ftplib import FTP
from cred import *

# Script for streestest

ftp_conn = FTP()

ftp_conn.connect(host=hostname, port=21)

ftp_conn.login(user=username, passwd=password)

counter = 0

# Testfile must exist!

try:
    file = open(file='./testfile', mode='rb')
    for i in range(10):
        filename = f'testfile{i+1}'
        ftp_conn.storbinary(cmd=f'STOR /stresstest/{filename}', fp=file)
        print(f'wrote file: {filename}')
        counter += 1

except FileNotFoundError:
    print('File does not exist!')

ftp_conn.quit()

print(f'Written {counter} files to {ftp_conn.host}')

谢谢您!

python loops ftplib
1个回答
0
投票

您必须对代码进行 2 次更正:

  • 在 for 中打开文件
  • 上传到服务器FTP后(
    STOR
    命令)关闭文件
    testfile

正确的代码是(我已经在我的系统上测试过):

from ftplib import FTP

# Script for streestest

ftp_conn = FTP()

ftp_conn.connect(host=hostname, port=21)

ftp_conn.login(user=username, passwd=password)

counter = 0

# Testfile must exist!

try:
    # move the open() inside the for loop
    #file = open(file='./testfile', mode='rb')  # <---- comment this instruction
    for i in range(10):
        file = open(file='./testfile', mode='rb')
        filename = f'testfile{i+1}'
        ftp_conn.storbinary(cmd=f'STOR /stresstest/{filename}', fp=file)
        print(f'wrote file: {filename}')
        counter += 1
        # close the file
        file.close()        # <----------- Add this close()

except FileNotFoundError:
    print('File does not exist!')

ftp_conn.quit()

print(f'Written {counter} files to {ftp_conn.host}')

使用上下文管理器

另一种方法是使用上下文管理器,如以下代码所示:

from ftplib import FTP

# Script for streestest

ftp_conn = FTP()

ftp_conn.connect(host=hostname, port=21)

ftp_conn.login(user=username, passwd=password)

counter = 0

# Testfile must exist!

try:
    for i in range(10):
        with open('./testfile', 'rb') as file:   # <---- here there is the context manager that opens the file
            filename = f'testfile{i+1}'
            ftp_conn.storbinary(cmd=f'STOR /stresstest/{filename}', fp=file)
            print(f'wrote file: {filename}')
            counter += 1

except FileNotFoundError:
    print('File does not exist!')

ftp_conn.quit()

print(f'Written {counter} files to {ftp_conn.host}')

通过上下文管理器,文件会自动关闭。

© www.soinside.com 2019 - 2024. All rights reserved.