当.csv文件不在使用Python的目录中时,如何添加错误处理消息?[duplicate]

f0ofjuux  于 2022-12-15  发布在  Python
关注(0)|答案(1)|浏览(112)

此问题在此处已有答案

How do I check whether a file exists without exceptions?(40个答案)
2天前关闭。
再次寻求您的帮助,当.csv文件不在目录中时,我如何添加错误处理消息。我该怎么做?抱歉,还在学习Python的东西,但非常感谢您提前。
完整代码:

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")

我试着在脚本中添加这个,但是即使文件不在目录中,它仍然在执行它的功能。

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')
uubf1zoe

uubf1zoe1#

有比你做的更容易的事:

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.")

相关问题