Navigation X
ALERT
Click here to register with a few steps and explore all our cool stuff we have to offer!



   2032

IS THIS GOOD TO CONVERT .TXT TO .JSON

by Planet - 07 November, 2020 - 08:11 PM
This post is by a banned member (Planet) - Unhide
Planet  
Heaven
2.526
Posts
829
Threads
5 Years of service
#1
okay so basically i found this video explaining how to convert txt files to json in python so I copied the code is that good guys? lemme know in the comments
 
Code:
 
import json
file = "cookies.txt"
dict = {}
with open(file) as fn:
    for d in fn:
        key, desc = d.strip().split(None, 1)
        dict[key] = desc.strip()
otfile= open("output.json", "w")
json.dump(dict,otfile)
otfile.close()
This post is by a banned member (devilxq) - Unhide
devilxq  
Registered
1
Posts
0
Threads
6 Years of service
#2
(This post was last modified: 10 November, 2020 - 11:33 PM by devilxq. Edit Reason: Fixing formatting )
Hey, it highly depends on how your input text file is formatted.
In general, this script ok it can work.

I can give you a few suggestions:
- I would suggest adding some error handling.
Python Documentation
DO NOT USE IT LIKE THAT
Code:
 
try:
    # you code which can raise exception
except:
    # do something when exception is raised 
# instead do this 

try:
    # you code which can raise AttributeError exception   
    # because you should understand what kind of error is going to be raised
except AttributeError:
    # do something when exception is raised


- try to not use variables without meaningful names. Single-letter or two-letter variable names are a bad idea in most cases.
- read about keyword and built-in function in python to get a better understanding of what names are reserver to be used by python itself.
What I mean by that, try to not use these names for your variables:
Code:
some, result, obj, file, false, true, results, objects, value, info, foo, objs, var, no, content, handle, val, items, etc....
- you don't have to define
Code:
file = "cookies.txt"
you can write "cookies.txt" directly in with context. You are not using this variable anywhere else so there is no reason for that.

- if you are opening one file with context menager, why don't do the same with second one?

Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
or
Sign in
Already have an account? Sign in here.


Forum Jump:


Users browsing this thread: 1 Guest(s)