2014-01-09 46 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

相关问题