Python: with open(filename, 'w') for a file that does not exist

15,177

Open with both w, w+ mode creates a file unless it exist. (truncates the file if it exist)

Difference between w and w+ is:

  • w: write only
  • w+: read + write
Share:
15,177

Related videos on Youtube

Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    Background

    I'm trying to write a script that creates a new LaTeX-file from a template I've made and I've run into a bit of a snag when it comes to using the following code:

    with open(filename + '.tex', 'w'):
        # Do stuff to filename.tex
        ...
    

    Consider the above as Option A.

    Here filename.tex, filename is a variable, (probably) doesn't exist within the directory from which the script is executed by the user. In Option A the file isn't created by the with open(...) statement. I obviously need to create filename.tex in this context.

    There is another way to open files, which is to be considered as Option B:

    f = open(filename.tex, 'w+')
    

    In the above statement the file is created if it does not exist.

    Hence, my question:
    Which of these options should I use if I mean to write clear, well written code, that adheres to the shared view of the Python community? (Pythonic)

    If Option A,
    I'd appreciate directions as to how to touch the file if it does not already exist, a link would be splendid. (Or include in the answer)

    • Kevin
      Kevin over 10 years
      "In Option A the file isn't created by the with open(...) statement." Strange, it gets created on my machine.
    • Admin
      Admin over 10 years
      @Kevin That is most peculiar indeed. I'll try a reboot!
    • Admin
      Admin over 10 years
      @Kevin Now it works, suddenly (after a reboot).
  • mfcabrera
    mfcabrera over 10 years
    In addition to that, if you really want to test the existence call the function with no mode parameters and it will fail if the file does not exist. I don't know of any Pythonic convention about it but is the recommended way to test the existence of a file. stackoverflow.com/questions/82831/…