python和json的新手。您將如何使用“打開”打開幾個 json 檔案,然后單獨閱讀。下面的代碼:
def read_json_file(filename):
with open("File1location/income","file2location/weather", "file3location/sun", 'r') as fp:
income = json.loads(fp.read())
return data
income = read_json_file(income)
print(len(income))
我需要列印每個檔案的長度,但我將如何隔離每個檔案?
謝謝
uj5u.com熱心網友回復:
要列印檔案的大小,只需執行此操作。無需打開或閱讀它們:
import os
for file in 'File1location/income', 'File2location/weather', 'File3location/sun':
print(f'{file} {os.path.getsize(file)} bytes')
uj5u.com熱心網友回復:
open不允許您傳遞多個檔案名 - 您總是打開一個檔案(請參閱檔案以確認)。
uj5u.com熱心網友回復:
在 Python 中處理檔案路徑時,我強烈建議使用該pathlib庫并匯入Path該類。
因此,例如,您需要一個串列(或通常是類似陣列的結構),其中存盤了所有 json 路徑。然后你可以寫這樣的東西:
import json
from pathlib import Path
json_paths = [Path("Fle1location/income.json") Path("file2location/weather.json"), Path("file3location/sun.json"))]
for path in json_paths:
with open(path, 'r') as f:
income = json.load(f)
print(len(income))
return創建函式/方法時使用關鍵字。
編輯
如果您想撰寫一個函式,我會編輯上面的代碼段:
def main():
for path in json_paths:
read_json_file(path)
def read_json_file(path):
with open(path, 'r') as f:
income = json.load(f)
print(len(income))
if __name__ == "__main__":
main()
重要的是要記住,擁有一個既回傳某些東西又具有副作用(即print)的函式被認為是一種不好的做法。一個函式/方法/類應該有一個單一的、定義明確的職責(參見單一職責原則)。所以在這種情況下,我只是添加了副作用而不回傳任何東西。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/474776.html
