2014-01-09 37 views
0
import random, time, pickle #Imports needed libaries 
from random import * #Imports all from random 

filename = ("char.txt") 
charList = []#Sets blank list 
charListstr = ''.join(charList)#Makes new list a string so it can be written to file 

def write(): 
     creation() 
     charw = open(filename, 'w') 
     charw.write(charListstr) 
     charw.close() 


def read(): 
     charr = open(filename, 'r') 
     lines = charr.read() 
     charr.close() 


def creation(): 
     charListinput = input("What would you like your charcater to be called?") 
     charList.append(charListinput) 

我想讓程序接受charcaters名稱,然後將該數據追加到列表中。然後我需要列表寫入.txt文件,以便用戶可以從外部讀取它。但是當函數運行時沒有錯誤,但是read()只是給出了一個空白輸出。我對Python很糟糕,所以任何幫助都會有用。寫入文件不起作用。當使用函數read()時,它不會輸出

+0

'charListstr'總是空的。如果您向該文件寫入空字符串,則在讀取文件時將返回空字符串。 – Matthias

回答

1

charListstr始終是空字符串,因爲你只評估一次,當時的列表是空的。你應該在你的write函數中加入你的列表。另外,你不會從read返回任何東西,所以即使你將某些東西保存到文件中也不會有輸出。

您需要先解決這兩個問題,然後纔能有一些輸出。

0

您沒有從read()加入return lines到最後。

您可能還想使用with語句來打開文件。它會自動關閉它,並且可以在將來避免一些麻煩。您還應該將該文件作爲參數傳遞給該函數,因爲它會使您的代碼更加靈活。

def read(file_name): 
    with open(file_name) as file: 
     lines = file.read() 
     return lines 
+0

好吧,我補充說,現在所有返回的是''? – Goggles998

+0

你想要讀什麼文件?在你的問題中向我們展示一個例子。 – IanAuld

相關問題