How to Create a File in Python

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

Start a new Python script file in your preferred editor.

Step

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

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.