Hi
How to get the path of home directory in windows?

I have the script that write log.txt in my windows 7 Desktop.

How can I change path in python to write log.txt in homedir directory? Is there any way to do it?

I tried with those 2 methods But its not work and its still write on windows Desktop?

LOG_FILENAME = 'log.txt'
#Method1
homedir = os.environ['ALLUSERSPROFILE']
LOG_FILENAME = homedir
LOG_FILENAME = 'log.txt'

#Method 2
homedir = os.path.expanduser('~')
LOG_FILENAME = homedir
LOG_FILENAME = 'log.txt'
#

Dani AI

Generated

On Windows, %ALLUSERSPROFILE% points to the shared profile (typically C:\ProgramData), not your personal home. If you later set the filename back to just log.txt, you are using a relative path again, which will be created in the process' current working directory. If your script is on the Desktop or your IDE starts in the Desktop, that explains why the file appears there. Build one absolute path to the file and use that variable consistently.

For modern Python, the most reliable cross-platform way is pathlib. It resolves the user home correctly on Windows, macOS, and Linux, and handles separators for you:

from pathlib import Path

log_path = Path.home() / 'log.txt'
log_path.write_text('Hello, log!\n', encoding='utf-8')

If you want to follow Windows guidelines and avoid writing directly to the profile root, target the per-user app data folder. This respects corporate setups and avoids permission surprises:

import os
from pathlib import Path

base = Path(os.getenv('LOCALAPPDATA', Path.home()))
appdir = base / 'MyApp'
appdir.mkdir(parents=True, exist_ok=True)
log_path = appdir / 'log.txt'

See the Python docs for pathlib.Path.home() and os.path.expanduser. For Windows folder guidance and variables like USERPROFILE/LOCALAPPDATA, refer to Microsoft’s Known folders and Environment variables docs.

Recommended Answers

All 7 Replies

I see that you are overwriting the LOG_FILENAME variable. Instead of adding "log.txt" to it, you are replacing it with "log.txt". That would make it write to the desktop I think. Try doing this instead (After getting the user's home directory):

LOG_FILENAME = os.path.join(homedir, "log.txt")
# returns: C:\Users\USERNAME\log.txt
# instead of just "log.txt"

At the very least you would have to "add" or "append" the filename to the users directory like this:

LOG_FILENAME = homedir + "log.txt"

But the os.path.join() method accounts for extra '/' or '\', which is why I use os.path.join where applicable.

Thanks Sir for your answer.
So as I understand you it will be as below is it right?

homedir = os.environ['ALLUSERSPROFILE']
LOG_FILENAME = os.path.join(homedir, "log.txt")

When I write those variable it create tmpConf.txt on my windows 7 Desktop, why?

homedir = os.environ['ALLUSERSPROFILE']
LOG_FILENAME = os.path.join(homedir, "log.txt")

can i see a couple things so I can help you better. first, in IDLE or whatever you're using to run your script, do a print LOG_FILENAME and let me see the output. second, show me the part where the file is actually written. From when you open it (with open(LOG_FILENAME, 'w') or however you're doing it), to when you close it (when you're done writing the file). I'm gonna boot up my Windows machine and make sure I'm not steering you wrong, but I'd like to see those two pieces of info..

Here, I booted into Windows (windows 8, i'll check windows 7 just to be sure though). This little script writes a simple text file to user directories using both the os.path.expanduser method, and the ALLUSERSPROFILE method. Both seem to work fine for me.

""" testuserdir.py
    Trys two different methods for writing a simple logfile to
    user directories in Windows.
"""

import sys, os, os.path

# short name for the test log.
short_filename = "testlog.txt"

def test_write(homedir):
    """ Trys to write sample text to a file """
    logfile = os.path.join(homedir, short_filename)
    print "Writing " + logfile
    try:
        with open(logfile, 'w') as flog:
            flog.write("Testing log file...\n")
    except (IOError, OSError) as exio:
        print "Unable to write file: " + logfile + '\n' + \
              str(exio)
        return False
    return True


def test_read(homedir):
    """ Trys to read from the sample file """
    logfile = os.path.join(homedir, short_filename)
    # Check the file
    print "Checking the file..."
    if os.path.isfile(logfile):
        print "    File contents:"
        try:
            with open(logfile) as flog:
                print '    ' + flog.read()
                return True
        except (OSError, IOError) as exio:
            print "Unable to read file: " + logfile + '\n' + \
                  str(exio)
    else:
        print "File did not exist!: " + logfile

    return False

def test_remove(homedir):
    """ Try to remove the test file """
    logfile = os.path.join(homedir, short_filename)
    if os.path.isfile(logfile):
        try:
            os.remove(logfile)
            print "Test file removed: " + logfile
            return True
        except (IOError, OSError) as exio:
            print "Unable to remove file:" + logfile + '\n' + \
                  str(exio)
    else:
        print "File doesn't exist!: " + logfile
    return False

def test_homedir(homedir):
    print ('-' * 60) + "\nTesting with home dir: " + homedir
    test_write(homedir)
    test_read(homedir)
    test_remove(homedir)

def main():
    homedir = os.environ['ALLUSERSPROFILE']
    test_homedir(homedir)
    homedir = os.path.expanduser('~')
    test_homedir(homedir)
    return 0

if __name__ == "__main__":
    ret = main()
    sys.exit(ret)


# Output of program when ran on my machine:
C:\scripts\python testuserdir.py
------------------------------------------------------------
Testing with home dir: C:\ProgramData
Writing C:\ProgramData\testlog.txt
Checking the file...
    File contents:
    Testing log file...

Test file removed: C:\ProgramData\testlog.txt
------------------------------------------------------------
Testing with home dir: C:\Users\Christopher
Writing C:\Users\Christopher\testlog.txt
Checking the file...
    File contents:
    Testing log file...

Test file removed: C:\Users\Christopher\testlog.txt

Confirmed, Windows 7 gets the same (correct) output. The problem lies elsewhere, so if this doesn't help you correct it you can show me the other parts I was asking about and we can continue from there.

chriswelborn Thanks for your wonderful answer again.
I appreciate your help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.