【问题标题】:Python creating text file on wrong pathPython在错误的路径上创建文本文件
【发布时间】:2020-08-09 21:06:51
【问题描述】:

我一直在尝试解决此问题,但找不到任何有用的解决方案。我正在尝试使用给定列表创建一个新的文本文件,该列表将列表的每个元素写入文本文件的每一行,但它会继续在我的“C:\ Users \ myuser”文件夹中创建文本文件,当它应该在存储程序的当前文件夹中创建它。谁能帮我解决这个问题,非常感谢。

代码:

def mention_text(usernames,users_per_line):
    print("Creating mentions text...")
    n = m = 0
    ments = []
    while m < len(usernames):
        m = m+users_per_line
        ments.append(str(" ".join(usernames[n:m])))
        n = m

    with open("mentions.txt", "w") as mentions:
        for i in ments:
            mentions.write(i + "\n")

    print("Done")

【问题讨论】:

  • 哪一行是您创建文件的?
  • @L.Papadopoulos with open("mentions.txt", "w") 作为提及:
  • 你看过这个吗? stackoverflow.com/a/5137509/5285732 - 您需要使用当前工作目录作为写入文件的路径

标签: python file text path


【解决方案1】:

我想通了,通过导入 os 并使用这行代码:

import os

def mention_text(usernames,users_per_line):
    print("Creating mentions text...")
    n = m = 0
    ments = []
    while m < len(usernames):
        m = m+users_per_line
        ments.append(str(" ".join(usernames[n:m])))
        n = m

    this_folder = os.path.dirname(os.path.abspath(__file__))  #this line locates the script in the folder where it is stored
    with open(os.path.join(this_folder, 'mentions.txt'), "w") as mentions: #here we use os.path.join to append the name of the file to the path of the script
        for i in ments:
            mentions.write(i + "\n")

    print("Done")

【讨论】:

    猜你喜欢
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 2012-04-22
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 2016-02-25
    相关资源
    最近更新 更多