Home > Back-end >  saving file with format
saving file with format

Time:02-07

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)

CodePudding user response:

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).

CodePudding user response:

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)
    file.write(users)
  •  Tags:  
  • Related