I'm relatively new to Python, so sorry if I butcher any terms or make dumb questions. My goal here is to rename any filename in a specific directory containing the string "&" to an "x". So far I've tried making python look for these files and print their filenames but get back an empty output, even though there's a test file that contains the string "&".
Here is my code:
import fnmatch
import os
for file in os.listdir('B:\\Music'):
if fnmatch.fnmatch(, '*&'):
print(file)
import os
directory = 'B:\\Music'
for basename in os.listdir(directory):
if '&' in basename:
os.rename(
os.path.join(directory, basename),
os.path.join(directory, basename.replace('&', 'x'))
)
As I said in the main post comment, you don't need fnmatch
, because you only wanted to tell if the basename contains &
. Using in
should be enough.
PS: Getting back to your title, you may refer to @adamgy's answer to get the correct way to use fnmatch
to match something in the future.