2

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.

lanzz
  • 42,060
  • 10
  • 89
  • 98
user3256847
  • 41
  • 1
  • 1
  • 6

3 Answers3

5

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.

acrosman
  • 12,814
  • 10
  • 39
  • 55
2

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.

phyce
  • 65
  • 5
0

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:

Pedro Walter
  • 623
  • 4
  • 11