Search code examples
pythonstdoutstdin

python stdout function returns none on last line


I have a bunch of lines in an input text file:

field1;field2;...fieldn

that I what to convert to an output.json whose lines are:

{field_name1:field1,field_name2:field2,...field_namen:fieldn}

So what I did is, using the following code:

from sys import stdin, stdout
import json

def txt_to_json(*args):
        for line in stdin:
                fields = [x.strip() for x in line.split(";")]
                stdout.write(json.dumps(dict(zip(args, fields))) + "\n")

in a shell (if input.txt contains three fields):

python -c "from process_files import *; print txt_to_json('field_name1','field_name2','field_name3')" < input.txt  > output.json

My output is fine except it contains None on the last line. I tried to modify my function but cannot get rid of this last None.

Thanks for the help


Solution

  • Your function does return None, you are printing the result of the function which then is piped to the file, remove the print() call:

    python -c "from process_files import *; txt_to_json('field_name1','field_name2','field_name3')" < input.txt  > output.json