ASMStephen ASMStephen - 1 year ago 58
Python Question

How do I replace bytes in multiple files in one directory recursively with Python 3.5.1?

I'm looking to achieve the following with multiple files in the same directory from one run of a script:

fh = open("*.bin", "r+b")
fh.write(bytes([0x4F, 0x67]))

My end goal is to have, say, that, when ran (from within the same directory as the files, or otherwise if need be), opens all files in the directory with a .bin extension, then replaces the first two bytes in each file with the same 2 bytes that I specify.

From what I've gathered (at least with Windows), an asterisk as a wildcard doesn't work. I can't seem to nail this down despite trying various solutions related to os.walk, glob, and others I've seen mentioned here on the site and research via the Google machine.

Thank you for any solutions or points of research you might offer!

EDIT: Thanks to the information from responses so far, I've built out what I was ultimately looking to achieve. Here's the final result, for those who might stumble upon this later.

# 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.write(bytes([0x4F, 0x67]))
name, ext = os.path.splitext(filename)
os.rename(filename, name + ".m32")

Answer Source

you need to do

os.listdir("your directory")  

which will give you a list of files. Then do your code on each file