I'm new to Python. I am converting evtx log files to xml, however, some of the evtx files have whitespace in their names and I get an error when the file conversion starts. One of the solutions is to manually remove all the whitespace from the evtx file names, but this is impossible when you deal with a large number of files.
I need to remove all the whitespace from file names in multiple directories. I am trying to rename the files by removing the whitespace with .replace(" ","")
, however, I keep getting an error:
FileNotFoundError: [Errno 2] No such file or directory:
Code:
dir_path = '/home/user/evtx_logs'
for dirpath, dirnames, filenames in os.walk(dir_path):
for f in filenames:
new_filename = f.replace(" ","")
os.rename(f,new_filename)
Is there any other alternative to rename or perhaps to ignore the white space in a file name?
Try printing out the values of your directory walk. You will notice that the filenames are not paths, they are just the names of the files. When you try to rename the file, you need to point your function to the entire path. Something like this:
for dirpath, dirnames, filenames in os.walk(dir_path):
for f in filenames:
filepath = os.path.join(dirpath, f)
new_filename = f.replace(" ","")
new_filepath = os.path.join(dirpath, new_filename)
os.rename(filepath, new_filepath)