-2

Hi guys I am trying to save my file in python... I dont know how to do it.. It came out the save file to be like this : 506882122734561843241851186242872

What I am trying to do is ["50688", "212273", "4561843", "241851", "18624", "2872"]

with open("output_data.txt", "w") as out_file:
    for user in users:
        out_string = ""
        out_string += str(user)
        out_file.write(out_string)
  • It looks you want to save JSON file. Is that the case? – buran Feb 07 '22 at 11:11
  • What was `user` before you wrote it to the file, and how was it produced? In order to help you, we need a [mre] including the input data... – Serge Ballesta Feb 07 '22 at 11:15
  • If that's really a JSON, see https://stackoverflow.com/questions/12309269/how-do-i-write-json-data-to-a-file – tevemadar Feb 07 '22 at 11:16
  • If you're not trying to save it into a JSON file, see https://stackoverflow.com/questions/38186365/python-convert-list-of-one-element-into-string-with-bracket – c21253 Feb 07 '22 at 11:18

2 Answers2

0

The loop you're using is stitching together each of the elements in your users list so you end up with one long string in out_string. You probably introduced this loop after you got an error message when trying to save the list straight to a file.

Instead, and as suggested in the comments, you could save the data as JSON:

import json

users = ["50688", "212273", "4561843", "241851", "18624", "2872"]

with open("output_data.txt", "w") as out_file:
    out_file.write(json.dumps(users))

output_data.txt will then contain:

["50688", "212273", "4561843", "241851", "18624", "2872"]

Note: this assumes that your original list is a list of strings, not integers (it wasn't clear from your question).

PangolinPaws
  • 670
  • 4
  • 10
  • just `json.dump(users, out_file)` is enough. The question is whether OP really want JSON and why not using correct file extension. – buran Feb 07 '22 at 11:25
  • that's true, I was trying to include as much of their original code as possible in case it was less of a leap – PangolinPaws Feb 07 '22 at 11:27
0

You are saving user variables without any delimiters.

You can try to use str.join to add commas like

users = ["0", "1", "2"]
users = ",".join(users)
print(users)  # should print '0,1,2'

You can also use repr to print string with quotes.

user = "3"
print(repr(user))  # should print '"3"'

Now you can combine both methods

with open("output_data.txt", "w") as file:
    users = map(repr, users)
    users = ", ".join(users)
    users = "[" + users + "]"
    file.write(users)
ventaquil
  • 2,780
  • 3
  • 23
  • 48