Python在错误路径上创建文本文件

2024-09-27 01:27:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在试图解决这个问题,但找不到任何有用的解决方案。我试图创建一个具有给定列表的新文本文件,该列表将列表中的每个元素写入文本文件的每一行,但它会继续在我的“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")

Tags: text文件夹元素列表line解决方案usersprint
1条回答
网友
1楼 · 发布于 2024-09-27 01:27:12

通过导入操作系统并使用以下代码行,我找到了答案:

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")

相关问题 更多 >

    热门问题