Question

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.

Was it helpful?

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.

OTHER TIPS

You can use open() to create files. Example:

open("log.txt", "a")

This will create the file if it doesn't exist yet, and will append to it if the file already exists.

Using open(filename, 'w') creates the file if it's not there. Be careful though, if the file exists it will be overritten!

You can read more details here:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top