此问题在此处已有答案:
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')
1条答案
按热度按时间uubf1zoe1#
有比你做的更容易的事: