我正在使用 AutoGen,并且添加了读写文本文件的工具(主要是因为不想浪费资源
def read_file(file_name: Annotated[str, "File name has to be json, txt or html"]) -> int:
if not file_name.endswith(".json") and not file_name.endswith(".txt") and not file_name.endswith(".html"):
return f"I can read only .json, .txt or .html files you asked for {file_name}. Use python to read other files."
if not os.path.exists(os.path.join(WORKING_DIR, file_name)):
return f"File {file_name} does not exist."
with open(os.path.join(WORKING_DIR, file_name), "r") as f:
return f.read()
def write_file(file_name: Annotated[str, "File name"], content: Annotated[str, "text or json content"]) -> int:
# verify that nested folders exists
if not os.path.exists(f"{WORKING_DIR}/{os.path.dirname(file_name)}"):
os.makedirs(f"{WORKING_DIR}/{os.path.dirname(file_name)}")
with open(f"{WORKING_DIR}/{file_name}", "w") as f:
return f.write(content)
我不喜欢我必须在这里处理工作?
我怎样才能做得更好?
您可以使用 os.getcwd() 请参阅此处:https://www.geeksforgeeks.org/python-os-getcwd-method/