创建文本文件并将其移动到另一个目录[我被卡住了]

时间:2018-10-17 06:13:02

标签: python python-3.x operating-system

我正在尝试为一个项目创建一些代码,在该代码中,我要求用户提供详细信息,然后问他们要投票给哪个总裁。现在我已经有5个文件夹,分别是总裁0,总裁1,总裁2,总裁3等。我遇到的麻烦是创建一个文本文件并将其移动到这些文件夹中。 这是我的一些代码:

elif vote_For_President=="4":
      open("President 4 vote"+str(Fn)+".txt", "a")

      with open("President 4 vote"+str(Fn)+".txt", "a") as a:

           a.write(list_Single_Name)

      os.path.join(a, "D:\pythonVoteHolder\President 4")

但是,有错误。说
文件“ C:\ Users \ Anonymous \ AppData \ Local \ Programs \ Python \ Python37 \ temp.py”,第51行,位于选民os.path.join(a,“ D:\ pythonVoteHolder \ President 4”)

1 个答案:

答案 0 :(得分:0)

尝试这样:

elif vote_For_President=="4":
    filename = "President 4 vote"+str(Fn)+".txt"
    filename = os.path.join("D:\pythonVoteHolder\President 4", filename)
    with open(filename , "a") as f:
        f.write(list_Single_Name)

这个想法是先创建一个包含整个路径的字符串变量,然后在with open()语句中打开它。您只能在此with open()语句中写入文件。通常,建议对变量使用更好的名称,好像您在混用a,将其放在with open()范围之外,因此在变量范围之外是未定义的。

相关问题