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

file, file-io, fopen, python, text

Solution

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

Problem

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)

Original source

Related problems