如何无需打开记事本,直接用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:
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
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!
- The
- To create an empty .py file:
type nul > empty_script.py(this is cleaner thanecho.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:
- Run this command:
copy con my_multi_line_script.py - 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}!") - When you’re done writing, press Ctrl + Z (you’ll see
^Zappear) and then press Enter. That saves your code and exits the interactive mode.
To make sure everything worked:
- Run
diragain—you should see your new.pyfile 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

