I'm building a web app on Django and I've implemented two functions, one to save csv files in a file directory on my PC, and the other is to read these files to view them in the website.
My problem is that I want to read csv files from the directory and display them but without the csv extension, I want their names to be the only thing visible, but I keep getting this error FileNotFoundError.
this is the function that saves the files to a directory
def openDataset(request):
if request.method == "GET":
return render(request, 'blog/upload_csv_ag.html')
if request.FILES.get("file2") is not None:
csv_file = request.FILES['file2']
if not csv_file.name.endswith('.csv'):
message='The uploaded file has to be CSV. Please try again.'
return render(request, 'blog/upload_csv_ag.html',{'message':message})
else:
save_path = 'C:/Users/user/Desktop/Fault Detection App/Uploaded_Datasets/'
file_name = csv_file.name
fs = FileSystemStorage(location=save_path)
file = fs.save(file_name, csv_file)
else:
message='no file is uploaded'
return render(request, 'blog/upload_csv_ag.html',{'message':message})
return render(request,'blog/upload_csv_ag.html',{'message':'Dataset Uploaded'})
and the function that reads the files from the directory
def read_datasets(request):
path = r"C:/Users/user/Desktop/Fault Detection App/Uploaded_Datasets/"
test = os.listdir(path)
path1, dirs, files = next(os.walk(path))
file_count = len(files)
print(file_count)
dataframes_list_html = []
file_names = []
index = []
for i in range(file_count):
temp_df = pd.read_csv(path files[i])
print(files[i])
dataframes_list_html.append(temp_df.to_html(index=False))
index.append(i)
for item in test:
if item.endswith(".csv"):
os.remove(os.path.join(path, item))
file_names.append(files[i])
return render(request,'blog/view_datasets.html',{'files': file_names})
CodePudding user response:
Extracting the names of the files
Step 1 : iterate through the directory
A simpler way would be to just do
for file in os.listdir(base_path)
Step 2 - remove the extension
You can use the method that evergreen suggested
Step 3 - store the processed string
Just append to your file_names list like you're doing and return the list in the response context
Reading and displaying the CSVs content
Actually reading and returning the content of the CSVs is slightly more involved, but your current approach by using pandas to read the files, and converting the dataframes to html tables should work just fine. Just remember to return the dataframes_list_html
list in the context as well so that you can access it in the template