How to Create a File in Python

Techwalla may earn compensation through affiliate links in this story. Learn more about our affiliate and product review process here.

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.

Advertisement

Step 1

Start a new Python script file in your preferred editor.

Video of the Day

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.

Advertisement

Advertisement

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.

Video of the Day

Advertisement

Advertisement

references

Report an Issue

screenshot of the current page

Screenshot loading...