【问题标题】:how to put a valid filepath as a function parameter in python如何在python中将有效的文件路径作为函数参数
【发布时间】:2016-05-03 01:54:37
【问题描述】:

我正在尝试在 python 3.5.1 中为基于文本的游戏编写一个保存/加载函数,我在这个站点上找到了一些有用的代码,不幸的是,这两个函数只需要一个文件路径作为参数之一。我正在学习python,并且对该站点和一般编码都相对较新,因此将不胜感激有关如何输入有效文件路径(以及在这种情况下有效文件路径的示例!)的帮助(再一次,我就像 Jon Snow)。相关方法贴在下面:

def __init__(self, name):
    self.name = name
    self.maxHealth = 100
    self.health = self.maxHealth
    self.baseAttack = 10
    self.credits = 10
    self.augs = 0
    self.weap = ["Basic Nanite Pack"]
    self.currWeap = ["Basic Nanite Pack"]
    global playerFile
    playerFile = {"name":self.name, "health":self.maxHealth, "maxHealth":self.health, "baseAttack":self.baseAttack,
                  "weapon":self.weap, "currWeap":self.currWeap, "credits":self.credits, "augs":self.augs}

def saveGame(playerFile, filepath):
    with open(filepath, 'w') as outfile:
        for name,num in playerFile.items():
            outfile.write("{};{};\n".format(num, name))

import csv
def loadGame(filepath):
    with open(filepath) as infile:
        # purposeful misspell for variable name
        playerFil = dict((v,k) for v,k,_ in csv.reader(infile, delimiter=';'))
    return playerFil

【问题讨论】:

    标签: python filepath


    【解决方案1】:

    文件路径是文件从头到尾的路径。 例如 c:\users\John\my_document.txt

    这是一个有效的文件路径,您通常应该像这样传递它:

    r'c:\users\John\my_document.txt'
    

    请注意,如果您不提供实际文件的路径 例如 c:\users\John Python 将无法打开任何文件,因为那将是目录路径。

    【讨论】:

      猜你喜欢
      • 2019-02-15
      • 1970-01-01
      • 2013-02-26
      • 2014-05-15
      • 1970-01-01
      • 2012-09-30
      • 1970-01-01
      • 2019-08-30
      • 2020-04-01
      相关资源
      最近更新 更多