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")
3
  • Which one is the line, that you create the file? Commented Aug 9, 2020 at 21:10
  • @L.Papadopoulos with open("mentions.txt", "w") as mentions: Commented Aug 9, 2020 at 21:13
  • Have you looked at this? stackoverflow.com/a/5137509/5285732 - you need to use the current working directory as the path for writing your files Commented Aug 9, 2020 at 21:31

1 Answer 1

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")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.