host = "html.com"
LNG = ENG, GED
input_folder = os.path.dirname(os.path.abspath(__file__))
output_folder = os.path.join(input_folder, 'output')
def get_filename(ext, base, sub_folder):
filename = '{}.{}'.format(base, ext)
return os.path.join(output_folder, sub_folder, filename)
subfolder = LNG + '\\' + host
ref_filename = get_filename('pcm', output_filename + '_ref', subfolder)
if not os.path.exists(ref_filename):
os.makedirs(ref_filename)
with open(ref_filename, 'wb') as f_pcm:
f_pcm.write(payload)
cur_filename = get_filename('pcm', output_filename, subfolder)
with open(cur_filename, 'wb') as f_pcm:
f_pcm.write(payload)
I am trying to check whether the path exists, if it does not exist then create one. I am creating output folder then language folder like ENG and GED. I am creating a another folder within that as html.com. later I am adding files like json and pcm files into it. In the above code (I did not add everything). everything is working fine except the last step.
It is not adding the files like _ref.pcm. it is creating a folder of it. can someone tell me what coudl be the mistake ?
os.makedirs() will always create a directory. This is what it is meant to do so this is expected behaviour. When you give it the filename it will treat it as a directory name and will create it as such. Change your code to the following:
def get_filename(ext, base, folder):
filename = '{}.{}'.format(base, ext)
return os.path.join( folder, filename)
output_folder = os.path.join( input_folder, 'output' )
subfolder = LNG + '\\' + host
output_folder = os.path.join( output_folder, subfolder )
if not os.path.exists(output_folder):
os.makedirs(output_folder);
# do note that output_filename is not defined anywhere
ref_filename = get_filename('pcm', output_filename + '_ref', output_folder)
with open(ref_filename, 'ab') as f_pcm:
f_pcm.write(payload)
The above code will first create the directory path and then create the file if it doesn't exist or it will open the one that already exists.
I hope that helps.