Issue
I would like to save my excel files to the directory pointed out by the user.
file_path = filedialog.askdirectory()
print(y)
for x in range(2, (int(y))+1):
newname = "%03d" % x
wb.save(f''+file_path+filewithoutextension+'- '+newname+'.'+fileextension)
print (filewithoutextension+'- '+newname+'.'+fileextension)
The following code doesn't work properly, as I have the situation in the image below.
Despite saving the file in the selected directory, the filename inherits the name of the directory folder and is saved in the same folder where the python file is located.
How can I fix it?
Solution
Looks like you just need to generate the file path correctly, you're missing a slash between file_path
and filewithoutextension
. I don't have full context for your code, so I can mostly only guess at the exact right implementation, but in general I recommend always using pathlib
when dealing with any kind of path. Give this a shot:
from pathlib import Path
file_path = filedialog.askdirectory()
print(y)
for x in range(2, (int(y)) + 1):
save_path = Path(file_path) / f"{file_without_extension}-{x:03}.{file_extension}"
wb.save(save_path)
print(save_path.name)
Also, here's a cleaner way to generate the necessary path from the original file path (requires Python 3.9.x):
new_path = Path(file_path) / original_file_path
save_path = new_path.with_stem(f"{original_file_path.stem}-{x:03}")
Answered By - Sam Morgan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.