簡體   English   中英

python-檢查迭代中的所有項目是否具有相同的屬性

[英]python - check if all items in an iteration have equal properties

我是python的新手,我正在編寫一個腳本,該腳本登錄ftp服務器以獲取文件列表,然后檢查同一文件夾中的所有文件是否具有相同的大小,但是我找不到在文件夾路徑相同的情況下比較大小的一種方法,這是到目前為止的操作:

import ftputil

server = 'xxxxxx'
user = 'xxxxxx'
password = 'xxxxxx'
root_folder = 'xxxxxx'

ftp = ftputil.FTPHost(server, user, password)
recursive = ftp.walk(root_folder, topdown=True, onerror=None)
for root_folder, subdir, files in recursive:
    for name in files:
        file_path = ftp.path.join(root_folder)
        file_size = ftp.stat(ftp.path.join(root_folder, name))[6]
        print(file_path, file_size)

誰能幫助我找出如何比較同一目錄中文件的大小?

假設您的代碼大部分正常工作。 我假設您要么想要True要么False,並且當您找到第一個差異時,您想要停止迭代。 例如:

same_size = None
common_size = False   # initialise

recursive = ftp.walk(root_folder, topdown=True, onerror=None)
for root_folder, subdir, files in recursive:
    for name in files:
        file_path = ftp.path.join(root_folder)
        file_size = ftp.stat(ftp.path.join(root_folder, name))[6]
        print(file_path, file_size)

        if common_size is None:      # execute on first file
            common_size = file_size
        elif common_size == file_size:
            same_size = True
        else
            same_size = False
            break

如果那里只有一個文件,則需要決定該怎么辦。

從空值開始迭代,將其設置在第一項,然后與該值進行比較。

expected_size = None
for root_folder, subdir, files in recursive:
    for name in files:
        file_size = ftp.stat(ftp.path.join(root_folder, name))[6]
        if expected_size is None:
            expected_size = file_size
        if expected_size != file_size:
            return True
    return False

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM