#Updated dec 2020 #It will creates Text file in path directory using name of file.txt import os path = 'some/path/to/file.txt' if not os.path.exists(path): with open(path, 'w') as f: f.write('Hello, world') #==== OR === mode = 'a' if os.path.exists(path) else 'w' with open(path, mode) as f: f.write('Hello, world!\n')
Here is what the above code is Doing:
1. Check if the file exists.
2. If it does, open it in append mode.
3. If it doesn’t, open it in write mode.
4. Write to the file.