نوشتن اسکریپت Python برای یک کار تکراری
کار تکراریای که با فایلها، Excel یا وب انجام میدهی را توصیف کن و یک اسکریپت Python تمیز و قابل اجرا بگیر، با توضیح نصب و نحوهٔ اجرا و مدیریت خطا.
- انتشار
- ۲۶ آبان ۱۴۰۵
- اجرا
- ۳ بار
نمونه خروجی
```python
import argparse
import sys
from pathlib import Path
import pandas as pd
def merge_excels(folder: Path) -> pd.DataFrame:
"""Read every .xlsx file in folder and stack them."""
files = sorted(folder.glob("*.xlsx"))
if not files:
raise FileNotFoundError(f"No .xlsx files in {folder}")
frames = [pd.read_excel(f).assign(source_file=f.name) for f in files]
return pd.concat(frames, ignore_index=True)
def main() -> int:
p = argparse.ArgumentParser()
p.add_argument("input", nargs="?", default=".")
p.add_argument("-o", "--output", default="merged.csv")
args = p.parse_args()
try:
merged = merge_excels(Path(args.input))
except (FileNotFoundError, ValueError) as e:
print(f"Error: {e}")
return 1
merged.to_csv(args.output, index=False, encoding="utf-8-sig")
return 0
…
چه چیزی لازم داری
توصیف کار، نمونه ورودی و خروجی دلخواه
متن پرامپت
پرامپت انگلیسیکدClaudeWrite a Python 3.11+ script that does the following task:
[Describe the task, e.g. read all .xlsx files in a folder, merge them into one sheet, and save as CSV]
Input example: [paste a small sample]
Desired output: [describe or paste]
Requirements:
- Single file, runnable with `python script.py`, with command-line arguments for input and output paths (use argparse) and sensible defaults.
- Use only the standard library plus at most these packages: [pandas, openpyxl, requests] if genuinely needed; list exact pip install commands.
- Handle errors explicitly: missing files, bad formats, empty inputs. Print clear messages, never a raw traceback for expected problems.
- Type hints, short docstrings, no global state, a `main()` guard.
- After the code, add a short section in Persian explaining how to install and run it, and the one thing most likely to go wrong.
If the task is ambiguous, ask one clarifying question before writing code.بعد از اجرا یا کپی، بگو برایت جواب داد یا نه.
چطور اجرا کنم
- دکمهٔ اجرا را بزن تا پرامپت در jostoju باز شود، یا متن را کپی کن و در ابزار دلخواهت بگذار.
- توصیف کار، نمونه ورودی و خروجی دلخواه را به آن بده.
- جایخالیهای داخل [ ] را با اطلاعات خودت پر کن.
- اگر نتیجه دقیقاً آن چیزی نبود که میخواستی، یک جمله توضیح اضافه کن و دوباره اجرا کن.
پرامپت انگلیسی؛ مدلها پرامپت انگلیسی را هم با ورودی فارسی خوب میفهمند. کلمهای ناآشنا بود؟ واژهنامه.