【问题标题】:Create text file in folder在文件夹中创建文本文件
【发布时间】:2021-12-30 08:46:42
【问题描述】:

我正在尝试创建一个使用我的程序中的变量命名的文本文件。唯一的问题是,当我使用变量命名目录时,我无法指定目录。 (vac_postcode 是我用来命名文件的变量)

centrebypostcode = open(C:\Users\Rich\Desktop\Assignment\Centre\vac_postcode + ".txt"', "a+")
            centrebypostcode.write("\n")
            centrebypostcode.write(vac_center)
            centrebypostcode.close()

我使用“a+”是因为如果文本文件不存在,我需要程序来创建它,但如果存在,它只是将我需要的内容附加到文本文件中。 (这是我对“a+”用法的理解)

很遗憾,open(r'C:\Users\Rich\Desktop\Assignment\Centre\vac_postcode + ".txt"', "a+" ') 也不起作用。

【问题讨论】:

  • 试试centrebypostcode = open("C:\Users\Rich\Desktop\Assignment\Centre\" + vac_postcode + ".txt", "a+")

标签: python file variables directory txt


【解决方案1】:

你必须将变量名保持在引用的字符串之外,将行改为

centrebypostcode = open(r"C:\Users\Rich\Desktop\Assignment\Centre" + "\\" + vac_postcode + ".txt", "a+")

已编辑:原始字符串文字不能有最后一个反斜杠,因此您需要单独连接。

【讨论】:

  • 由于编辑队列已满,无法编辑。那不会产生错误吗?在".txt" 之后不应有'
  • 多亏了你,我才能在我的程序中完成很多其他的事情!
【解决方案2】:

看来引用是错误的。

试试这个

centrebypostcode = open(r"C:\Users\Rich\Desktop\Assignment\Centre\{}.txt".format(vac_postcode), "a+")

【讨论】:

    【解决方案3】:

    我只是尝试更具描述性

    filenames = ["my_file1","my_file2"]
    for filename in filenames:
        filename = f"C:\Users\Rich\Desktop\Assignment\Centre\vac_postcode\{filename}.txt"
        with open(filename, "a+") as fh:
            fh.write("Hello world")
    

    【讨论】:

      猜你喜欢
      • 2015-01-11
      • 2021-03-30
      • 1970-01-01
      • 2020-03-03
      • 2022-06-13
      • 2018-12-02
      • 1970-01-01
      • 2013-12-29
      • 1970-01-01
      相关资源
      最近更新 更多