Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

python - File handling with functions?

So I got this code that is supposed to sort a dictionary within a json file alphabetically by key:

import json

def values(infile,outfile):
    with open(infile):
        data=json.load(infile)
        data=sorted(data)
        with open(outfile,"w"):
            json.dump(outfile,data)

values("values.json","values_out.json")

And when I run it I get this error:

AttributeError: 'str' object has no attribute 'read'

I'm pretty sure I messed something up when I made the function but I don't know what.

EDIT: This is what the json file contains:

{"two": 2,"one": 1,"three": 3}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are using the strings infile and outfile in your json calls, you need to use the file description instance, that you get using as keyword

def values(infile,outfile):
    with open(infile) as fic_in:
        data = json.load(fic_in)
        data = sorted(data)
        with open(outfile,"w") as fic_out:
            json.dump(data, fic_out)

You can group, with statements

def values(infile, outfile):
    with open(infile) as fic_in, open(outfile, "w") as fic_out:
        json.dump(sorted(json.load(fic_in)), fic_out)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...