2

I've been using Python for a few months, but I'm sort of new to Files. I would like to know how to save text files into my Documents, using ".txt".

Brandon Minnick
  • 12,264
  • 13
  • 61
  • 111
  • Possible duplicate of [Python Save to file](https://stackoverflow.com/questions/9536714/python-save-to-file) – lyxal Apr 12 '18 at 01:16

2 Answers2

1

You can create files using the open() function, which takes two arguments, the path to the file and the mode. Since you want to make a new file, you should be using the w+ mode.

with open("path_to_my_documents\\filename.txt", 'w+') as f:
    f.write("a string you want to save")
kindall
  • 168,929
  • 32
  • 262
  • 294
Mark Tyler
  • 393
  • 1
  • 9
  • [here](https://www.tutorialspoint.com/python/python_files_io.htm) is a pretty intuitive guide to basic input/output in Python. – patrick Apr 12 '18 at 00:21
  • @kindall I was under the impression that 'w' didn't create a new file but I guess I'm wrong – Mark Tyler Apr 12 '18 at 00:25
0

If you do not like to overwrite existing file then use a or a+ mode. This just appends to existing file. a+ is able to read the file as well

pramesh
  • 1,774
  • 1
  • 14
  • 27