python stdout函数在最后一行返回none

时间:2017-01-04 14:26:00

标签: python stdout stdin

我在输入文本文件中有很多行:

field1;field2;...fieldn

我要将其转换为output.json,其行为:

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

所以我做的是,使用以下代码:

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")
shell中的

(如果input.txt包含三个字段):

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

我的输出很好,但最后一行包含None。我试图修改我的功能,但无法摆脱这最后的无。

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

您的函数确实返回None,您正在打印函数的结果,然后通过管道传输到该文件,删除print()调用:

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