简体   繁体   English

python stdout函数在最后一行不返回任何内容

[英]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: 我该将其转换为以下内容的output.json:

{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): 在外壳程序中(如果input.txt包含三个字段):

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. 我试图修改我的函数,但不能摆脱最后的None。

Thanks for the help 谢谢您的帮助

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM