0

Let's say I'm using these codes to write something to a file.

with open('somefile.txt', 'a') as the_file:
    the_file.write('Hello\n')

In this case, must 'somefile.txt' be an existing file or a file that we just created by writing a 'hello' message?

tripleee
  • 175,061
  • 34
  • 275
  • 318

2 Answers2

1

As mentioned here :

To create a new file in Python, use the open() method, with one of the following parameters:

"x" - Create - will create a file, returns an error if the file exist

"a" - Append - will create a file if the specified file does not exist

"w" - Write - will create a file if the specified file does not exist

So in your case, using open('somefile.txt', 'a') with a as a second parameter, you are creating a file if not exists.

Hamza Abdaoui
  • 2,029
  • 4
  • 23
  • 36
0

When you are using "with open", it will open the file if it is already present in the folder and if is not present in the folder it will create a new file in that folder where you are running this file.

tripleee
  • 175,061
  • 34
  • 275
  • 318