2017-07-14 74 views
-1

所以,我試圖讓事情簡單:如何將信息返回到其他文件?

shopping_list = [] 
print("Enter 'done' to stop adding items.") 

while True: 
    new_item = input("> ") 

    if new_item.lower() == "done": 
     break 
    shopping_list.append(new_item) 
    print("Here's your list:") 

    for item in shopping_list: 
     print(item) 

我能,而不是打印此,該列表返回到另一個文件,以顯示該文件?我是新手,不確定是否有可能(儘管所有代碼都是可行的,對吧?)。我的目標是讓列表顯示並保存,以便隨時訪問。

+0

寫功能。有功能'返回'列表。讓另一個文件中的代碼調用該函數。 – user2357112

+0

所以你的意思是你想將列表寫入文本文件?如果這樣看[this](http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python)網站。否則,請你澄清你的問題 –

+0

謝謝你,@Professor_Joykill,這是豐富的。 – Cybertether

回答

1

對於初學者,您需要將代碼放入函數中。否則,你將無法「返回」任何東西。

def foo(): 
    .... 
    return shopping_list 

所以,你的代碼將是這樣的:

def foo(): 
    while True: 
     new_item = input("> ") 

     if new_item.lower() == "done": 
      break 
     shopping_list.append(new_item) 

    return shopping_list 

而且,你會打電話給你的功能是這樣的:

my_shopping_list = foo() 

一旦函數返回時,my_shopping_list是一個列表的購物物品,你可以隨心所欲地做。

另請注意,我從循環中刪除了打印語句。如果你需要它們,請隨時添加它們,但我認爲這就是你不想要的。


現在,當你說文件時,我假設你只是想在同一個程序的其他地方。但是,如果你確實想從另一個python腳本調用這個函數,這裏就是你會做什麼:

A.py

def foo(): 
    ... # entire function definition here 

B.py

創建兩個Python腳本。第一個容納您的foo功能。第二個叫它。


另外,如果你要打印你的購物清單到實際文件(把你的話字面上這裏),你會怎麼做:

foo(): 
    ... 
    with open('cart.txt', 'w') as f: 
     for i in shopping_list: 
      f.write(i + '\n') 

這會將你的項目文件。

0

如果你的意思是你想運行列表中的文本文件的Python腳本之外,你可以做到以下幾點:

outfile = open(file, "w") 
CODE 
outfile.write(shoppping_list) 

outfile.close() 
0

你可以試試這個方法:

def func(): 
    shopping_list = [] 
    print("Enter 'done' to stop adding items.") 

    while True: 
     new_item = input("> ") 

     if new_item.lower() == "done": 
      break 
     shopping_list.append(new_item) 

    return shopping_list 
if __name__ == '__main__': 
    print("Here's your list:") 

    outfile = open('test.txt', "w") 
    shopping_list = func() 

    # outfile.write(shopping_list) 

    for item in shopping_list: 
     # print(item) 
     outfile.write(item + "\n") 

    outfile.close() 
相關問題