File_Name = "Invoice_Dmart"
Folder-Name = "c:\Documents\Scripts\Bills"
How to check if the specific filename exist in the "Folder-Name" with any extension, If Yes Get the full path in a variable.
Code i have been using:
import os.path
if not os.path.Folder-Name(File_Name):
print("The File s% it's not created "%File_Name)
os.touch(File_Name)
print("The file s% has been Created ..."%File_Name)
Please Suggest the best possible way to solve it.
CodePudding user response:
I would use pathlib.Path
here. It provides convenient apis to iterate over the directories(.iterdir()
) and also to get the filename without extension(.stem
). So you can do somewhat like this.
>>> from pathlib import Path
>>> [str(child) for child in Path(your_folder_name).iterdir() if child.stem == your_file_name]
CodePudding user response:
try the code below
import os
file_name = "Invoice_Dmart"
folder_name = "c:\Documents\Scripts\Bills"
# os.path.splitext() split filename and ext
# os.listdir() list all files in the given dir
filenames_wo_ext = [os.path.splitext(elem)[0] for elem in os.listdir(folder_name)]
if file_name not in filenames_wo_ext:
print("The File %s it's not created "% file_name)
with open(file_name, 'w'):
print("The file %s has been Created ..."% file_name)
CodePudding user response:
Before, you should fix the syntax of the variable Folder-Name
to Folder_Name
.
I guess you can solve the problem by simply adding the two strings through a slash, and using the function os.path.exists() like:
import os.path
File_Name = "Invoice_Dmart"
Folder_Name = "c:\Documents\Scripts\Bills"
path = Folder_Name "\" File_Name
exist = os.path.exists(path)
print(exist)
It worked for me, hope it does for you aswell.