-1

I have a couple dictionaries that I want to write to their own text files and I want to be able to open them up separately (notepad).

This is the code I have used to save the dictionaries to their respective files.

f = open('example.txt', 'w')
f.write(str(dict))
f.close

Is this the correct way to do so and if so, where do these textfiles get saved to?

bbalzano
  • 33
  • 5
  • Possible duplicate of [Python Print String To Text File](https://stackoverflow.com/questions/5214578/python-print-string-to-text-file) – busybear Jan 04 '19 at 19:05
  • The file will be written relative to the script path. If this is running on a server, make sure that the user that executes the script has access to write to the directory. – mbunch Jan 04 '19 at 19:06

2 Answers2

0

If you only want to view them in notepad and not reuse them then that might be the right way. However if you want to read them back into python then I suggest using a serialiser like json:

import json
with open('example.txt', 'w') as f:
    json.dump(dict_, f)

The files end up in the current working directory which can be deduced like so:

import os
print(os.getcwd())

You can change to an absolute path for example.txt to make sure you know where you put it.

Tips: don't use "dict" as a variable name as it's a builtin class.

SimonF
  • 1,855
  • 10
  • 23
0

I agree with the previous answer. It totally depends on what you are planning to use the text file for. Even if it is just to look at the dictionary contents at a later point, sometimes styling the output is better.

As for where the files are written, the way you have it right now example.txt will be in the current working directory (CWD), ie, where you are running the script. For instance, if you are in documents/projects/foo/ and you run python3 main.py, example.txt would be written to documents/projects/foo/example.txt If instead you are in documents/projects and you run python3 foo/main.py, example.txt would be be written to documents/projects/example.txt. If you want the file to always be written to the same place, you should use a constant filepath. os.path has a lot of tools if you want to do it that way.

  • Not correct, the current working directory depends on how the script is called and what is done previously in the script (like changing the cwd). Consider this way of calling the script `python3 subfolder/main.py` – SimonF Jan 04 '19 at 19:27