我想在同一目錄中打開所有具有相同擴展名 (.dat) 的檔案。
這是我當前的代碼:
path = Path(".") # current directory
extension = ".dat"
file_with_extension = next(path.glob(f"*{extension}"))
if file_with_extension:
with open(file_with_extension, encoding='utf-8') as infile, open('462888.dat', 'w', encoding='utf-8') as outfile:
for line in infile:
if '462888' in line:
outfile.write(line)
我當前代碼的問題是它只能打開和讀取一個擴展名為 (.dat) 的檔案。我如何閱讀所有這些?
uj5u.com熱心網友回復:
結果 frompath.glob(f"*{extension}")實際上是一個可迭代的,您可以在 for 回圈中迭代并逐個獲取每個檔案名。
這樣,您應該在檔案名上添加一個 for 回圈并打開每個檔案名,讀取行(使用另一個 for 回圈),然后寫入輸出檔案。
像這樣的東西:
from pathlib import Path
path = Path(".") # current directory
extension = ".dat"
with open('462888.dat', 'w', encoding='utf-8') as outfile:
for filename in path.glob(f"*{extension}"):
with open(filename, encoding='utf-8') as infile:
for line in infile:
if '462888' in line:
outfile.write(line)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/514437.html
上一篇:SEEK_FAILURE如果檔案超過4.1GB,SetFilePointer失敗怎么辦
下一篇:我上傳的圖片沒有保存在存盤檔案中
