create a file in the script using python

createfile, python

Solution

Open can be used in a several modes, in your case you have opened in read mode ('r'). To write to a file you use the write mode ('w').

So you can get a file object with:

open('1.txt', 'w')

If 1.txt doesn't exist it will create it. If it does exist it will truncate it.

Problem

I am new to python. I wanted to know if I could create a text file in the script itself before writing into. I do not want to create a text file using the command prompt. I have written this script to write the result into the file ``` with open('1.txt', 'r') as flp: data = flp.readlines() ``` however I know that 1.txt has to be created before writing into it. Any help would be highly appreciated.

Original source