如何使用 Python 3.5.1 递归替换一个目录中多个文件中的字节?

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")  

这将为您提供文件列表。然后在每个文件上做你的代码