2016-09-19 67 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