2016-09-19 68 views
0

我已经将Python中的主要功能applyin“主”功能的CSV输出,说:保存在蟒蛇

def main(): 
    "some code here" 

if __name__ == '__main__': 
    main() 

然后我得到这样一个结果:

[['This is my car not yours'], ['He answered me sorry'], ['no problem'], ['\nYou are crazy'], ['All cars are the same'], etc...] 

我想将结果保存在txt和csv文件中,以便稍后保存相同的结构:平方括号,单词,逗号等。我该怎么做?提前致谢。

+0

您可以使用Python的csv模块https://docs.python.org/3/library/csv.html 它可以将列表转换成CSV –

+1

并直接打印为“python”,使用漂亮打印(pprint)另一种可能性是python urscript.py> data.txt这是shell你使用,将标准输出重定向到一个文件 –

+0

我不明白'main()'函数与csv有什么关系,老实说... – martin

回答

0

希望这是你想要的东西:

def main(): 
    return [['This is my car not yours'], ['He answered me sorry'], ['no problem'], ['\nYou are crazy'], ['All cars are the same']] 

if __name__ == '__main__': 
    with open('output.txt', 'w') as f: 
     a = ('').join(str(main())) 
     f.write(a) 
+0

感谢Boris,但是,在应用你的代码后txt文件是空的。如何改进? – mlosada

+0

我刚编辑我的答案。你应该把'print'语句改成'return'。因为我不知道main()里面的代码,所以这是我最好的猜测。 – zipa