How to Create a File in Python

By Mikhail Polenin

Python is an interpreted programming language that has the potential to create programs in all operating systems. Before hopping into making advanced programs that read and write to files you must learn to create a file in Python. To create a file you call a function called "open" and specify that you want to write to it. If the file doesn't exist Python simply creates it.

Step 1

Start a new Python script file in your preferred editor.

Step 2

Write the following in the first line of the Python script: file = "file.dat." Python "knows" if you want to declare a string or other variable type, so you don't have to specify this. Replace "file.dat" with another file path, if you wish.

Step 3

Make a new line and write "fptr = open(file, "w")." This creates the file since it doesn't exist. Once created the file's address in the computer's memory copies to "fptr" and gives you control over what gets written into it.

Tips & Warnings

  • Don't forget to close the file. Use "fptr.close()" at any time after you have finished writing to the file. If you do not close the file it occupies computer memory until the script finishes.