![](/img/trans.png)
[英]How to exclude files in path directory using pathlib in python the proper way?
[英]Get number of files in directory with pathlib python
我有兩個目錄,其中包含 csv 文件。 兩者的長度應該相同,因為我正在使用 zip 循環它們。 因此,我檢查它們的長度是否相同。 代碼如下所示:
from pathlib import Path
def check():
base = Path('home/user/src/log').rglob('*.csv')
test = Path('home/user/src/log').rglob('*.csv')
print(list(base))
if len(list(base)) != len(list(test):
print(f"Wrong number of files in {str(base)} and {str(test)}")
return -1
for base, test in zip(base, test):
x = pd.read_csv(base)
y = pd.read_csv(test)
print(x)
print(y)
if __name__ == '__main__':
check()
list(base)
提供文件列表,但它也靜默殺死程序。 因此,如果我有print(list(base))
它將在 base 中打印文件,然后程序終止。 str(base)
也不起作用,但這是因為我還沒有找到一種方法來打印出目錄路徑,而程序隨后不會終止。 在不殺死程序的情況下獲取列表長度和打印目錄的任何提示。
注意:我現在可以使用“os”,但如果可能的話,我想使用 pathlib
rglob
返回一個生成器。 生成器上的調用list
會消耗所有項目。
但是,您最初可以將其轉換為列表,然后繼續使用該列表:
from pathlib import Path
def check():
base = list(Path('home/user/src/log').rglob('*.csv'))
test = list(Path('home/user/src/log').rglob('*.csv'))
print(base)
if len(base) != len(test):
print(f"Wrong number of files in {str(base)} and {str(test)}")
return -1
for base, test in zip(base, test):
x = pd.read_csv(base)
y = pd.read_csv(test)
print(x)
print(y)
if __name__ == '__main__':
check()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.