-1

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')
  • @AbirbhavG, the link you provided gave me an idea. It is working when the file is in the directory, however it doesn't work when the file is not in the directory. I tried inserting this if os.path.isfile(f): print("Good") else: print("Bad") – QuickSilver42 Dec 13 '22 at 11:17

1 Answers1

0

There is easier than what you doing:

import os

file_found = False

for file in os.listdir("C:/Folder"):
    if file.endswith(".csv"):
        file_found = True
        break

if file_found:
    print("There's .csv file in C:/Folder.")
else:
    print("Error! There's no .csv file in C:/Folder.")
Lucas Fernandes
  • 1,360
  • 2
  • 8
  • 12