我想在特定文件目录中保存一个 .text 文件,用于存储某人输入的信息

I want to save a .text file in a specific file directory for information entered by someone

每当调用此函数时,所有信息都会保存到列表 playerInfo 中。现在我想将这个列表保存为一个 .text 文件,名称是用户输入的名称 (p_name) 以供以后在目录中使用: C:\Users\Vatiekakie\OneDrive\Documents\CourseWorkProject\Players

###代码###

    def savePlayer(self):
        # blank list to hold player info
        playerInfo = []
        # loop through data and pull out each info
        playerInfo.append(self.p_name)
        playerInfo.append(self.p_prfname)
        playerInfo.append(self.p_dob)
        playerInfo.append(self.p_height)
        playerInfo.append(self.p_nr)
        playerInfo.append(self.p_placeob)
        playerInfo.append(self.p_weight)

        p_name = self.p_name.text()


# to save playerInfo to .text file

        playerFileName = "p_name"
        playerFile = open(playerFileName, "w")
  
with open(playerFileName + ".txt", "a") as file:
  for item in playerInfo:
    file.write(item + "\n")

文件自动关闭 (此代码改为 playerFile = open(playerFileName, "w")

检查下面提到的代码片段是否适合您:

# to save playerInfo to .text file
playerFilePath = 'C:\Users\Vatiekakie\OneDrive\Documents\CourseWorkProject\Players'
playerFileName = p_name
outputPath = os.path.join(playerFilePath, playerFileName) ## import os library for this line to work
with open(outputPath, "w") as f:
    for item in playerInfo:
        f.write("%s\n" % item)