I'm getting an error that I can't understand... The output looks like this:
Renaming chr1/tests/test-ch1.py to chr1/tests/test-ch1_ref.py...
Traceback (most recent call last):
File "/Users/eomiso/Workspace/miso-projects/scripts/append_ref_to_filename.py", line 18, in <module>
os.rename(old_path, new_path)
ValueError: embedded null byte
Code:
import os
import re
# Define the path to the directory containing the files
target_dir = "chr1/tests"
suffix = "_ref"
# Compile a regular expression to match file extensions
ext_pattern = re.compile(r"\.[^.]+$")
for root, dirs, files in os.walk(target_dir):
for filename in files:
if ext_pattern.search(filename) and not filename.endswith(suffix):
old_path = os.path.join(root, filename)
ext = ext_pattern.search(old_path).group()
new_path = os.path.join(root, ext_pattern.sub(f"{suffix}\\0", filename)) + ext
print(f"Renaming {old_path} to {new_path}...")
os.rename(old_path.strip(), new_path.strip())
The code is a simple script that adds a suffix to all files. I can't seem to understand why on earth there is could be a null character in the new_path? I have the file created already... And since the output is well printed just before the os.rename
function, I can't see why the null byte (or character) is mingled into the new_path
.
A bit of more context: before adding .encode("utf-8").strip() to the code, I got
ValueError: embedded null byte` error.