[英]How do I replace bytes in multiple files in one directory recursively with Python 3.5.1?
我希望通過一次腳本運行在同一目錄中的多個文件中實現以下目標:
fh = open("*.bin", "r+b")
fh.seek(0)
fh.write(bytes([0x4F, 0x67]))
fh.close()
我的最終目標是讓 myByteReplacement.py 在運行時(從與文件相同的目錄中,或者如果需要的話),打開目錄中帶有 .bin 擴展名的所有文件,然后替換前兩個每個文件中的字節數與我指定的 2 個字節相同。
從我收集到的(至少在 Windows 中),星號作為通配符不起作用。 盡管嘗試了與 os.walk、glob 和我在網站上看到的其他解決方案相關的各種解決方案並通過 Google 機器進行研究,但我似乎無法確定這一點。
感謝您提供的任何解決方案或研究要點!
編輯:多虧了到目前為止的回復信息,我已經建立了我最終想要實現的目標。 這是最終結果,供以后可能會偶然發現的人使用。
# This script looks for files of a specific filetype (.bin) in a specified
# directory (C:/Convert). It then replaces the first two bytes of those
# files with 2 bytes that I specify (0x4F, 0x67). Finally, it renames those
# files to what their actual extension should be (.m32).
import os, re
path = "C:/Convert"
os.chdir( path )
files = os.listdir( path )
for filename in files:
if re.match('.*\.bin', filename):
fh = open(filename, "r+b")
fh.seek(0)
fh.write(bytes([0x4F, 0x67]))
fh.close()
name, ext = os.path.splitext(filename)
os.rename(filename, name + ".m32")
你需要做
os.listdir("your directory")
這會給你一個文件列表。 然后在每個文件上執行您的代碼
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.