写入文件不起作用。当使用函数read()时,它没有给出任何输出


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)

我正在尝试让程序接受字符名称,然后将该数据附加到列表中。然后,我需要列表写入.txt文件,以便用户可以在外部读取它。但是当函数运行时,没有错误,但 read() 只给出一个空白输出。我对Python很糟糕,所以任何帮助都会很有用。

charListstr始终是空字符串,因为您只计算一次它,此时列表为空。您应该在write函数中加入您的列表。此外,您不会从 read 返回任何内容,因此即使您确实将某些内容保存到文件中,您也不会有输出。

您需要先解决这两个问题,然后才能获得一些输出。

您不会从末尾添加return lines read()返回任何内容。

您可能还希望使用 with 语句打开文件。它会自动关闭它,并且可以在将来节省一些麻烦。您还应该将文件作为函数中的参数传递,因为它会使您的代码更加灵活。

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

最新更新