Python script home directory

Getting the path of home directory in Python

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?

  • 2 Contributors
  • 7 Replies
  • 7K Views
  • 1 Day Discussion Span
  • Latest Post 10 Years Ago Latest Post by tony75

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: …

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.

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

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

Читайте также:  Python eval source code

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 

Источник

How to get the home directory in Python

In this article, we will learn how to get the path of the home directory in Python. We will use two built-in functions to get the home directory.

The home directory contains multiple files for a given user of the system. Look at the two below scripts to get the home directory in Python. We will look at two different modules of Python such as the os module and pathlib module.

Use os module to get the Home Directory

os module provides os.path.expanduser(‘~’) to get the home directory in Python. This also works if it is a part of a longer path like ~/Documents/my_folder/. If there is no ~ in the path, the function will return the path unchanged. This function is recommended because it works on both Unix and Windows. It returns the argument with an initial component of (tilt) ~ or ~user replaced by the user’s home address.

import os print(os.path.expanduser('~'))

Use the pathlib module to get the Home Directory

The pathlib module provides path.home() to get the home directory in Python. This function works fine if your Python version is Python 3.4+. It returns a new path object having the user’s home directory.

from pathlib import Path print(Path.home())

Conclusion

In this article, we learned two different ways to get the home directory of a user’s system in Python. One way was using os.path.expanduser(‘~’) and another way was pathlib.Path.home() . Do check your script to avoid errors.

Источник

How to find the real user home directory using Python?

On a multiuser operating system, a home directory is a file system location that holds the files specific to a particular user.

A login directory is another name for a home directory.You may obtain the home directory using Python in a number of ways.

Using os module

The os.path.expanduser() function in Python provides the most straightforward method for retrieving the user home directory across all platforms. The Python os module offers os.path.expanduser(«) to retrieve the home directory. This also functions if it is a part of a longer path. The function will return the path unchanged if there is no ~ in the path.

Example — Home Directory Path

Following is an example to find the home directory using os.path.expanduser() function −

import os home_directory = os.path.expanduser( '~' ) print( home_directory )

Output

Following is an output of the above code −

Example — File Inside Home Directory

Use os.path.join to create the path C:\Users\Lenovo\Downloads\Works −

import os home_directory = os.path.expanduser( '~' ) path = os.path.join( home_directory, 'Documents', 'mysql_access' ) print( path )

Output

Following is an output of the above code −

C:\Users\Lenovo\Documents\mysql_access

Example — ~ Substitution

If you already have a string path, such as C:\Users\Lenovo\Downloads\Works, where you wish to replace with the home directory path, you can put it in directly to.expanduser() instead of using the safe way to generate paths, which is os.path.join() −

import os path = os.path.expanduser('~\Documents\mysql_access') print( path )

Output

Following is an output of the above code −

C:\Users\Lenovo\Documents\mysql_accessy

Using pathlib module

The pathlib module in Python can also be used to obtain the user’s home directory.

Example — Home Directory Path

Following is an example to find the home directory path.home() function −

from pathlib import Path home_directory = Path.home() print( f'Path: home_directory> !' )

Output

Following is an output of the above code −

Example — File Inside Home Directory

Using.joinpath, you can also quickly create paths inside the user’s home directory () −

from pathlib import Path path = Path.home().joinpath( 'Documents', 'mysql_access' ) print(path)

Output

Following is an output of the above code −

C:\Users\Lenovo\Documents\mysql_access

Example — ~ Substitution

Use.expanduser() if you already have a string path, such as /Documents/mysql_access, where you want to replace with the path to your home directory −

from pathlib import Path path_string = '~\Documents\mysql_access' path = Path(path_string).expanduser() print(path)

Output

Following is an output of the above code −

C:\Users\Lenovo\Documents\mysql_access

Источник

Оцените статью