1

I am trying to create a new .txt file in python by the following method if the file does not already exists:

company_name_file = open(company_name_file.txt, "r")

company_name_file.close()

But, it is not creating a new file if the file name does not exists. Any help would be appreciated!

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Pressing_Keys_24_7
  • 1,755
  • 2
  • 7
  • 33
  • 5
    Does this answer your question? [open() in Python does not create a file if it doesn't exist](https://stackoverflow.com/questions/2967194/open-in-python-does-not-create-a-file-if-it-doesnt-exist) – Tomerikoo Jun 15 '20 at 09:28
  • it is showing the following error message: NameError: name 'company_name_file' is not defined – Pressing_Keys_24_7 Jun 15 '20 at 09:32
  • 2
    You need to wrap the filename in quotes, to make it a string: `"company_name_file.txt"`. – Gino Mempin Jun 15 '20 at 09:32
  • @GinoMempin Got it thanks! – Pressing_Keys_24_7 Jun 15 '20 at 09:33
  • Does this answer your question? [Can't open file: "NameError: name is not defined"](https://stackoverflow.com/questions/5908067/cant-open-file-nameerror-name-filename-is-not-defined) – Gino Mempin Jun 15 '20 at 09:39
  • 1
    Please don't edit the answer into the question. Also, you should *always* include the error message in the question, as it could make it easier/clearer for people to debug the problem. – Gino Mempin Jun 15 '20 at 09:40

1 Answers1

0

You need to change the "r" to a "w+". r represents the read mode and w represents the write mode Currently, your code is trying to read a file rather than write a file.

with open("company_name_file.txt", "w+") as company_name_file:
    company_name_file.write("Test")
chumbaloo
  • 671
  • 6
  • 16