0

i've been trying to fix this but i can't find any useful solution. I'm trying to create a new text file with a given list that writes each element of the list on each line of the text file, but it keeps creating the text file on my "C:\Users\myuser" folder, when it should be creating it in the current folder where the program is stored at. Can anyone please help me fix this, Thanks so much.

Code:

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")
Javier Jerez
  • 360
  • 4
  • 16

1 Answers1

0

I figured it out, by importing os and using this line of code:

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")
Javier Jerez
  • 360
  • 4
  • 16