Seeking for your assistance again on how I can add an Error Handling Message when the .csv file is not in the directory. How do I this? Sorry, still learning stuff in Python but thank you very much in advance.
Full code:
import os
import pandas as pd
import openpyxl
import tkinter
from tkinter import messagebox
root = tkinter.Tk()
root.withdraw()
directory = 'C:/Path1'
ext = ('.csv')
for filename in os.listdir(directory):
f = os.path.join(directory, filename)
if f.endswith(ext):
head_tail = os.path.split(f)
head_tail1 = 'C:/Path2'
k =head_tail[1]
r=k.split(".")[0]
p=head_tail1 + "/" + r + " - .csv"
mydata = pd.read_csv(f, engine='python')
# to pull columns and values
new = mydata[["A","B","C","D"]]
new = new.rename(columns={'D': 'F'})
new['F'] = 1
print(new.columns)
new["B"] = (pd.to_datetime(new["B"], format="%d-%b", errors="coerce").dt.strftime("%#m-%#d").fillna(new["B"]))
new.to_csv(p ,index=False)
#to merge columns and values
merge_columns = ['A', 'B', 'C']
merged_col = ''.join(merge_columns).replace('ABC', 'G')
new[merged_col] = new[merge_columns].astype(str).apply(lambda x: '.'.join(x), axis=1)
new.drop(merge_columns, axis=1, inplace=True)
new = new.groupby(merged_col).count().reset_index()
new.to_csv(p, index=False)
messagebox.showinfo("Done.")
os.chdir("C:/Path2")
for file in os.listdir():
if file.endswith(".xlsx"):
if os.path.exists("Master.xlsx"):
os.rename("Master.xlsx", "Old_Master.xlsx")
os.rename(file, "Master.xlsx")
I tried adding this on the script but it is still doing its function even if the file is not in the directory.
import os
import pandas as pd
import openpyxl
import tkinter
from tkinter import messagebox
root = tkinter.Tk()
root.withdraw()
directory = 'C:/Path1'
ext = ('.csv')
for filename in os.listdir(directory):
f = os.path.join(directory, filename)
if f.endswith(ext):
#added line###############
if os.path.isfile(directory):
print("File does exist at this time")
else:
print("No such file exists at this time")
head_tail = os.path.split(f)
head_tail1 = 'C:/Path2'
k =head_tail[1]
r=k.split(".")[0]
p=head_tail1 + "/" + r + " - .csv"
mydata = pd.read_csv(f, engine='python')