You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何无需打开记事本,直接用CMD创建并保存.py文件?

Hey there! As someone who's been in your shoes starting out with Python and CMD, I’ll walk you through exactly how to create .py files right from the command line without opening Notepad first. Let’s break it down into simple, actionable steps:

Step 1: Navigate to the directory where you want to create your .py file

First, you need to tell CMD where you want your file to live. Use the cd (change directory) command to move around:

  • To go to your Desktop: cd Desktop
  • To go up one folder level: cd ..
  • To see what’s in your current directory (to confirm you’re in the right spot): dir
Step 2: Create your .py file directly in CMD

You’ve got two easy ways to do this—pick the one that fits what you need:

Method 1: Use echo for quick, single-line (or empty) files

If you just want a simple script with one line, or even an empty file to edit later, echo works perfectly:

  • To create a script with content: echo print("Hello, Python!") > my_first_script.py
    • The > symbol tells CMD to write the text before it into the file after it. If the file already exists, this will overwrite it!
  • To create an empty .py file: type nul > empty_script.py (this is cleaner than echo. for empty files)
  • To add more lines to an existing file without overwriting: echo print("Another line!") >> my_first_script.py (use >> instead of > to append)

Method 2: Use copy con for writing multi-line code interactively

If you want to write a few lines of code right in CMD without switching to another program, copy con is your friend:

  1. Run this command: copy con my_multi_line_script.py
  2. Now you can type your code line by line, pressing Enter after each line. For example:
    print("First line of code")
    name = input("What's your name? ")
    print(f"Hello, {name}!")
    
  3. When you’re done writing, press Ctrl + Z (you’ll see ^Z appear) and then press Enter. That saves your code and exits the interactive mode.
Step 3: Check that your file was created correctly

To make sure everything worked:

  • Run dir again—you should see your new .py file listed.
  • To view the content of your file right in CMD, use type my_first_script.py

And if you ever want to edit the file later (without manually opening Notepad first), you can just run notepad my_first_script.py—it’ll launch Notepad directly with your file loaded!

内容的提问来源于stack exchange,提问作者Vishal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:51:18