Создание файла через командную строку windows


Загрузить PDF


Загрузить PDF

Командная строка — удобный инструмент для быстрого и эффективного выполнения задач в Windows. Это полнофункциональный и часто недооцененный инструмент компьютерной системы. Действия в командной строке осуществляются без мышки, поэтому она идеально подходит для людей, предпочитающих работать за клавиатурой. Из этой статьи вы узнаете, что собой представляет Командная строка и как с ее помощью выполнять базовые задачи. Прочитав данную статью, вам будет намного проще выполнять базовые задачи через Командную строку.

  1. Изображение с названием Create and Delete Files and Directories from Windows Command Prompt Step 1

    1

    Запустите Командную строку. Нажмите на меню «Пуск» и найдите строку поиска. Введите в нее «командная строка» или «cmd». Дважды нажмите на Командную строку в списке результатов, чтобы запустить утилиту. По умолчанию Командная строка имеет следующий вид: C:\users\Username>.

  2. Изображение с названием Create and Delete Files and Directories from Windows Command Prompt Step 2

    2

    Создайте новую папку. Воспользуйтесь командой mkdir для создания новой папки. Чтобы создать папку, необходимо ввести «mkdir-> имя папки». В приведенном выше примере новая папка wikihow была создана с помощью команды: mkdir wikihow.

  3. Изображение с названием Create and Delete Files and Directories from Windows Command Prompt Step 3

    3

    Измените текущий активный каталог. Чтобы перейти в другую папку, воспользуйтесь командой «cd», или change directory (изменить каталог). Для этого введите следующее: cd -> название папки. В нашем примере нужно ввести cd wikihow. Как показано на картинке выше, новая строка будет иметь следующий вид: C:\users\Ivan\wikihow>.

  4. Изображение с названием Create and Delete Files and Directories from Windows Command Prompt Step 4

    4

    Проверьте содержимое папки. Чтобы проверить содержимое текущей папки, воспользуйтесь командой dir. Просто введите dir и нажмите Enter, после чего в Командной строке отобразится список содержимого папки.

  5. Изображение с названием Create and Delete Files and Directories from Windows Command Prompt Step 5

    5

    Очистите данные с экрана. Для этого воспользуйтесь командой cls. Просто введите cls и нажмите Enter, чтобы очистить содержимое с экрана. Как показано на примере выше, на экране останется лишь командная строка.

  6. Изображение с названием Create and Delete Files and Directories from Windows Command Prompt Step 6

    6

    Создайте новый файл. Чтобы создать новый файл, введите команду NUL >. Введите NUL > название файла и нажмите Enter, чтобы создать новый пустой файл. В приведенном выше примере было введено NUL> newfile.

  7. Изображение с названием Create and Delete Files and Directories from Windows Command Prompt Step 7

    7

    Создайте еще один файл. Теперь повторите шаг 6, чтобы создать еще один файл. Назовите этот файл newFile1. Для этого необходимо ввести команду NUL> newFile1.

  8. Изображение с названием Create and Delete Files and Directories from Windows Command Prompt Step 8

    8

    Проверьте содержимое папки. Теперь проверьте содержимое папки с помощью команды dir. Как показано на примере сверху, папка wikihow теперь содержит два новых файла: newFile и newFile1.

  9. Изображение с названием Create and Delete Files and Directories from Windows Command Prompt Step 9

    9

    Удалите файлы. Чтобы удалить файлы, воспользуйтесь командой del. Введите del -> название файла, чтобы удалить конкретный файл. Введите del newFile, чтобы удалить файл с названием newFile. Теперь проверьте содержимое папки wikihow и убедитесь, что файл newFile был удален. Очистите данные с экрана командой cls.

  10. Изображение с названием Create and Delete Files and Directories from Windows Command Prompt Step 10

    10

    Переместитесь выше по дереву каталогов. Чтобы выполнить следующий шаг (удалить папку), вам сначала нужно покинуть текущий активный каталог. Для этого воспользуйтесь версией команды для смены папки. Введите команду cd.., чтобы перейти в родительский каталог, не вводя его название. Введите: cd.. как показано на примере выше. Обратите внимание, что в строке теперь написано C:\users\Brian>, а это значит, что вы больше не находитесь в папке wikihow.

  11. Изображение с названием Create and Delete Files and Directories from Windows Command Prompt Step 11

    11

    Удалите пустую папку. Чтобы удалить папку, воспользуйтесь командой rmdir. Пока вы находитесь в папке, ее нельзя будет удалить (смотри шаг 10). Если папка пустая (в ней нет файлов), ее можно удалить, просто введя команду rmdir -> имя папки. В нашем примере в папке wikihow все еще находится файл newFile1, так что команда rmdir не сработает. Как показано на примере выше, если папка не пустая, вы получите сообщение об ошибке.

  12. Изображение с названием Create and Delete Files and Directories from Windows Command Prompt Step 12

    12

    Удалите папку с файлами. Чтобы удалить папку, в которой содержатся файлы, воспользуйтесь измененной командой rmdir. Введите команду rmdir /s wikihow. Введите rmdir /s wikihow и нажмите Enter. Появится окно подтверждения удаления папки, введите Y или N. Введите Y, чтобы подтвердить удаление, или N, чтобы отменить его. Когда вы введете Y, папка и все ее содержимое будут удалены из системы.

    Реклама

Советы

  • Команды можно вводить как заглавными, так и строчными буквами.
  • Используйте команду CLS для регулярной очистки экрана. Так вам будет намного удобнее работать.

Реклама

Предупреждения

  • Для работы с командной строкой нужна практика, а также повышенное внимание при удалении или перемещении файлов. Поскольку в командой строке при удалении файлов не бывает предупреждений или второй попытки, убедитесь, что удаляете именно те файлы и что важные документы останутся нетронутыми.

Реклама

Что вам понадобится

  • Компьютер, работающий на операционной системе Windows
  • Клавиатура

Источники

Об этой статье

Эту страницу просматривали 136 454 раза.

Была ли эта статья полезной?


Download Article


Download Article

Learning how to do simple file management at the Command Prompt (cmd) comes in handy when you’re learning to code. When you create files and folders at the command line, you can access, use, and manipulate those folders and files in Windows apps. We’ll show you how to create folders (directories) and text files at the Windows Command Prompt, and teach you commands for deleting unneeded files and folders.

  1. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 10

    1

    Open the Command Prompt. The easiest way to do this is to press Win + S to activate the search bar, type cmd, and then click Command Prompt in the search results.

  2. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 11

    2

    Go to the directory in which you want to create the file. The prompt will open to C:\Users\YourName by default. If the directory is somewhere else, type cd path_to_directory and press Enter. Replace path_to_directory with the actual directory location.[1]

    • For example, if you want to create a file on the Desktop, type cd desktop and press Enter.
    • If the directory you’re looking for isn’t in your user directory (e.g., C:\Users\YourName), you’ll have to type in the whole path (e.g., C:\Users\SomeoneElse\Desktop\Files).

    Advertisement

  3. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 12

    3

    Create an empty file. If you don’t want to create an empty file, skip to the next step.[2]
    To create an empty file:

    • Type type nul > filename.txt.
    • Replace filename.txt with whatever you want to call your new file. The «.txt» part indicates that this is a plain text file. Other common file extensions include «.docx» (Word document), «.png» (empty photo),and «.rtf» (rich text document). All of these file types can be read on any Windows computer without installing additional software.
    • Press Enter.
  4. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 13

    4

    Create a file containing certain text. If you don’t want to create a file with certain text inside, skip to the next step.[3]
    Use these steps to create a plain text file that you can type into:

    • Type copy con testfile.txt, but replace testfile with the desired file name.[4]
    • Press Enter.
    • Type some text. This is a rudimentary text editor, but it’s good for quick notes or code. You can use the Enter key to go to the next line.
    • Press Control + Z when you’re finished editing the file.
    • Press the Enter key. You’ll see «1 file(s) copied,» which means your file is now saved with the name you created.
    • Another way to do this is to run this command: echo enter your text here > filename.txt.
  5. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 14

    5

    Create a file that’s a certain size. If you don’t want to create a file that’s a specific size, skip this step.[5]
    To create a blank text file based on byte size, use this command:

    • fsutil file createnew filename.txt 1000.
    • Replace filename with the desired file name, and 1000 with the actual number of bytes you’d like the file to be.
  6. Advertisement

  1. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 15

    1

    Open the Command Prompt. The easiest way to do this is to press Win + S to activate the search bar, type cmd, and then click Command Prompt in the search results.

  2. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 16

    2

    Go to the directory containing the file you want to delete. The prompt will open to C:\Users\YourName by default. If the file is somewhere else, type cd path_to_directory and press Enter. Replace path_to_directory with the actual directory location.

    • For example, if you want to delete a file from the Desktop, type cd desktop and press Enter.
    • If the directory you want to view isn’t in your user directory (e.g., C:\Users\YourName), you’ll have to type in the whole path (e.g., C:\Users\SomeoneElse\Desktop\Files).
  3. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 17

    3

    Type dir and press Enter. This displays a list of all files in the current directory. You should see the file you want to delete in this list.

    • Using Command Prompt to delete files results in the files being deleted permanently rather than being moved to the Recycle Bin. Exercise caution when deleting files via Command Prompt.
  4. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 18

    4

    Type del filename and press Enter. Replace filename with the full name and extension of the file you want to delete.[6]
    File names include file extensions (e.g., *.txt, *.jpg). This deletes the file from your computer.

    • For example, to delete a text file entitled «hello», you would type del hello.txt into Command Prompt.
    • If the file’s name has a space in it (e.g., «hi there»), you will place the file’s name in quotations (e.g., del "hi there").
    • If you get an error that says the file cannot be deleted, try using del /f filename instead, as this force-deletes read-only files.
  5. Advertisement

  1. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 1

    1

    Open the Command Prompt. The easiest way to do this is to press Win + S to activate the search bar, type cmd, and then click Command Prompt in the search results.[7]

  2. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 2

    2

    Go to the directory in which you want to create the new directory. The prompt will open to C:\Users\YourName by default. If you don’t want to create a new directory here, type cd path_to_directory and press Enter. Replace path_to_directory with the actual directory location.[8]

    • For example, if you want to create a directory on your Desktop, you would type in cd desktop and press Enter.
    • If the directory you’re looking for isn’t in your user directory (e.g., C:\Users\YourName), you’ll have to type in the whole path (e.g., C:\Users\SomeoneElse\Desktop\Files).
  3. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 3

    3

    Type mkdir NameOfDirectory at the prompt. Replace NameOfDirectory with the name of the directory you wish to create.[9]

    • For example, to make a directory named «Homework», you would type mkdir Homework.
  4. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 4

    4

    Press Enter. This runs the command to create a folder with the desired name.

  5. Advertisement

  1. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 5

    1

    Open the Command Prompt. The easiest way to do this is to press Win + S to activate the search bar, type cmd, and then click Command Prompt in the search results.[10]

  2. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 6

    2

    Go to the folder containing the directory you want to delete. The prompt will open to C:\Users\YourName by default. If the directory you want to delete is somewhere else, type cd path_to_directory and press Enter.[11]
    Replace path_to_directory with the actual directory location.

    • For example, if you want to delete a directory from your Desktop, type cd desktop.
    • If the directory isn’t in your user directory (e.g., C:\Users\YourName), you’ll have to type in the whole path (e.g., C:\Users\SomeoneElse\Desktop\Files).
  3. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 7

    3

    Type rmdir /s DirectoryName. Replace DirectoryName with the name of the directory you want to delete.[12]

    • For example, if you’re trying to delete your «Homework» folder, you’d type in rmdir /s Homework here.
    • If the directory’s name has a space in it (e.g., «Homework assignments»), place the name in quotations (e.g., rmdir /s "Homework assignments").
  4. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 8

    4

    Press Enter to run the command.[13]

    • If you try to delete a directory that contains hidden files or directories, you’ll see an error that says «The directory is not empty.» In this case, you’ll have to remove the «hidden» and «system» attributes from the files inside the directory. To do this:[14]

      • Use cd to change into the directory you want to delete.
      • Run dir /a to view a list of all files in the directory and their attributes.
      • If you’re still okay with deleting all of the files in the directory, run attrib -hs *. This removes special permissions from the undeletable files.
      • Type cd .. and press Enter to go back one directory.
      • Run the rmdir /s command again to delete the folder.
  5. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 9

    5

    Press y and then Enter to confirm. This will permanently remove the directory.[15]

  6. Advertisement

Add New Question

  • Question

    How can I create directories?

    Subhodeep Roy

    Subhodeep Roy

    Community Answer

    If you are creating a directory in C drive, the command will be»C:\MD {the name of the directory/folder}» then press Enter.

  • Question

    How do I create a folder using CMD?

    Community Answer

    Navigate to where you want the subfolder created and type «mkdir «.

  • Question

    How do I create a test file under the sub folder?

    Community Answer

    Change directory into the new sub folder and then on the next line, create your new test file. For example: cd mysubfolder $ type nul > newtextfile.txt

See more answers

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

Video

Thanks for submitting a tip for review!

  • Using Command Prompt to delete files results in the files being deleted permanently rather than being moved to the Recycle Bin. Exercise caution when deleting files via Command Prompt.

Advertisement

About This Article

Article SummaryX

1. Use the mkdir command to create a folder.
2. Use rmdir /s to delete a folder.
3. Use the copy con or echo command to create a file.
4. Use del to delete a file.
For tips on how to create a file inside a folder, read on!

Did this summary help you?

Thanks to all authors for creating a page that has been read 1,417,089 times.

Is this article up to date?

on January 3, 2009

We can create files from command line in two ways. The first way is to use fsutil command and the other way is to use echo command. If you want to write any specific data in the file then use echo command. If you are not bothered about the data in the file but just want to create a file of some specific size then you can use fsutil command.

To create file using echo

echo some-text  > filename.txt

Example:

C:\>echo This is a sample text file > sample.txt
C:\>type sample.txt
This is a sample text file
C:\>

To create file using fsutil

fsutil file createnew filename number_of_bytes

Example:

C:\data>fsutil file createnew sample2.txt 2000
File C:\data\sample2.txt is created
C:\data>dir
01/23/2016  09:34 PM     2,000 sample2.txt
C:\data>

Limitations

Fsutil can be used only by administrators. For non-admin users it throws up below error.

c:\>fsutil file /?
The FSUTIL utility requires that you have administrative privileges.
c:\>

Создание и чтение текстовых файлов в командной строкеЕсли вы оказались без доступа к чему-либо кроме командной строки или Windows PowerShell и по какой-то причине вам требуется возможность создания или чтения текстовых файлов, это вполне реализуемо, причем более чем одним методом.

В этой инструкции подробно о работе с текстовыми файлами в командной строки или PowerShell (разумеется, можно и в Терминале Windows) — создание и сохранение текстовых файлов, их вывод и чтение в консоли.

Создание текстовых файлов в командной строке

Возможность создания текстовых файлов доступна как в командной строке (cmd.exe), так и в PowerShell. Начнем с первого варианта.

Во всех случаях учитывайте, что при использовании кириллицы потенциально возможны проблемы с кодировкой, а в некоторых случаях кодировка может отличаться при использовании разных команд.

Команда ECHO

Команда командной строки echo предназначена для вывода текстовых сообщений в окне консоли, например, при выполнении сценария в bat-файле, но может быть использована и для вывода текста в файл, благодаря возможности использования оператора «>» для перенаправления вывода из консоли в файл.

Пример команды:

echo Содержимое текстового файла > file.txt

В результате её выполнения в текущей рабочей папке командной строки будет создан файл с именем file.txt и содержимым «Содержимое текстового файла».

Создание текстового файла с помощью команды echo

COPY CON

Команда copy с параметром con позволяет скопировать содержимое консоли в файл. Использование возможности будет состоять из следующих шагов:

  1. Введите команду
    copy con имя_файла.txt

    файл не будет создан, но после выполнения указанной команды у вас появится возможность набрать содержимое этого файла, которое по завершении процесса будет в него сохранено.

  2. Курсор переместится на строчку ниже, и вы сможете набирать текст так, как делаете это обычно, включая перенос строки. Создание текстового файла с помощью copy con
  3. Для завершения набора и сохранения текстового файла нажмите сочетание клавиш Ctrl+Z, а затем — Enter. Это добавит отметку конца файла и сохранит его в текущей папке с указанным на 1-м шаге именем. Сохранение текстового файла с помощью copy con

Создание текстового файла в PowerShell

PowerShell также имеет набор встроенных командлетов для сохранения текстовых данных в файл.

Out-File

Использование Out-File в PowerShell по своей функциональности сходно с оператором перенаправления вывода в командной строке. Вывод консоли перенаправляется в заданный файл.

Пример использования:

"Текстовая строка" | Out-File -FilePath .\file.txt

В этом примере в текущей папке PowerShell будет создан файл с именем file.txt и содержимым «Текстовая строка».

New-Item

Создание нового текстового файла в PowerShell возможно с помощью командлета New-Item. Пример команды, в которой создается текстовый файл file.txt, содержащий «Текстовая строка» в текущем расположении:

New-Item -Path . -Name "file.txt" -ItemType "file" -Value "Текстовая строка"

Создание текстового файла с помощью New-Item в PowerShell

Set-Content и Add-Content

Ещё два командлета PowerShell для работы с текстовыми файлами:

  • Set-Content — перезаписывает содержимое файла
  • Add-Content — добавляет содержимое в конце выбранного файла

Их использование можно увидеть на примере следующей команды:

Add-Content -Path .\file.txt -Value "Ещё одна текстовая строка"

Добавление текста к файлу в PowerShell

Вывод (чтение) текстового файла в командной строке и PowerShell

Теперь перейдем к способам просмотреть текстовые файлы в командной строке или PowerShell. Как и в предыдущем случае, учитывайте, что для файлов, содержащих кириллицу, возможны проблемы с отображением символов в правильной кодировке.

TYPE

Самый простой вариант — использование команды TYPE с указанием пути к файлу, который нужно отобразить в консоли, например:

type file.txt

Вывод текстового файла с помощью команды type

MORE

Если файл объемный и содержит большое количество строк, используйте команду more, например:

more file.txt

Выполнив команду, вы увидите часть содержимого текста, которая помещается в окне консоли, далее вы можете использовать следующие клавиши:

Вывод текстового файла с помощью команды more

  • Enter — для отображения следующей строки файла.
  • Пробел — для отображения следующих строк документа, которые поместятся в активное окно консоли.
  • P — Показать следующие N строк. После нажатия этой клавиши с последующим указанием количества строк, будет выведено соответствующее количество строк текстового документа.
  • S — пропустить следующие N строк, работает аналогично предыдущему варианту.
  • Клавиша «=» — для отображения текущего номера строки.
  • Q — для прекращения выполнения команды more.

Get-Content

Вывести содержимое текстового файла в PowerShell можно с помощью Get-Content с указанием пути к файлу, например:

Get-Content file.txt

Чтение текстового файла с помощью Get-Content в PowerShell

Также вы можете выводить определенные строки файла, с помощью команд вида (вывод первых или последних 10 строк соответственно):

Get-Content file.txt | Select-Object -First 10
Get-Content file.txt | Select-Object -Last 10

Или присвоить содержимое файла переменной и вывести конкретную строку:

$file_text = Get-Content file.txt
$file_text[2]

Текстовый редактор edit.com в Windows

Помимо использования ручного ввода команд, вы можете использовать консольные текстовые редакторы — сторонние в версиях для Windows, такие как Vim, Nano, Kinesics Text Editor или даже старый встроенный edit.com (может отсутствовать в вашей версии системы и требовать патча NTVDMx64).

Knowing how to conduct rudimentary file management at the Command Prompt comes in useful when you’re starting to code. Any file you make from the Command Prompt persists in multiple areas of Windows—this means that generating an index or document at the prompt fixes things so that you can access, utilize, and control that catalog or record in the Windows platform.

There are two ways to create files from the command line. The first method uses the fsutil command, and the second method uses the echo command.

Create File with Echo Command

|echo some-text > filename.txt

Create File with Fsutil Command

|fsutil file createnew filename number_of_bytes

Step-by-Step Process to Create Files via Command Line

STEP 1: Launch the command prompt.

The quickest way to implement this is to open the search bar by pressing Win + S, type cmd, and then select Command Prompt.

STEP 2: Choose the folder where you wish to save the file.

By default, the prompt will open under C:UsersYourName. Suppose the folder is elsewhere; type the cd path to the folder and hit Enter. Modify the way to the folder with the actual folder path.

STEP 3: Make a blank file.

Type |type nul > filename.txt

Modify filename.txt with a name according to your preference and hit Enter.

The “.txt” extension means that it’s a plain text file.

“.docx” (Word document), “.png” (empty photo), and “.rtf” (rich text document) are other popular file extensions.

All of these file formats may be viewed on any Windows system without the need for extra software.

Step 4: Make a file with certain text in it.

Replace testfile with the appropriate file name in copy con testfile.txt. Hit Enter.

Enter any text. This is a basic text editor, but it’s adequate for brief notes or coding. To move to the following line, use the Enter key.

Press Control + Z after you’re done editing the file.

Hit the Enter key. You should notice “1 file(s) copied,” meaning your file has been saved using the name you chose.

OR

|echo enter your text here > filename.txt.

STEP 5: Make a file of a specific size.

Avoid this step, if you don’t wish to deliver a document of a specific size. Utilize the accompanying order to produce a clear text document dependent on its byte size.

|fsutil file createnew filename.txt 1000

Replace filename with the name of your wish and 1000 with the exact number of bytes you want the document to be.

Other useful articles:

  • Basic Windows CMD commands
  • Cool CMD Commands Tips and Tricks
  • Best CMD Commands for Hacking
  • CMD Commands for Wireless Network Speed
  • Useful Keyboard Shortcuts for CMD
  • What Info about My Laptop Can I Check with CMD and How?
  • Getting Started with CMD Windows
  • TOP-12 Command-Line Interview Questions (Basic)
  • Command-Line Interview Questions (Advanced)
  • CMD Commands to Repair Windows
  • CMD Commands to Speed Up Computer
  • CMD Commands for MAC OS
  • How Does the Command Line Work?
  • MS-Dos Interview Questions in 2021
  • Windows OS Versions and History
  • Recent Windows Versions Compared
  • Basic Windows Prompt Commands for Every Day
  • Windows Command Line Cheat Sheet For Everyone
  • Windows Command Line Restart
  • Windows Command Line for Loop
  • Windows Command — Change Directory
  • Windows Command — Delete Directory
  • Windows Command Line – Set Environment Variable
  • How Do I Run Command Line
  • Windows Command Line Create File

  • Создать загрузочную флешку с mac os через windows
  • Создание эталонного образа windows 10
  • Создать образ системы windows server
  • Создать загрузочную флешку для windows 11 pro 64
  • Создание флешки для установки windows 10 rufus