A basic program which writes the user name who has logged in the windows machine:

######################
#    User info       #
######################

import os 
import datetime
from time import  strftime

def foo(): 
    usr_log = os.environ ['USERNAME']
    sys_log = os.environ ['USERPROFILE']
    current_time = strftime("%a, %d %b %Y %H:%M:%S")
    dt_str = str (datetime.date.today())


    filename = usr_log + '_' + dt_str + '.' + 'txt'
    write_line= "File created by %s on %s" % (usr_log, current_time)
    write_line1 = "The default path is %s" % sys_log
    file = open(filename, 'w')
    file.truncate()

    file.write('%s\n %s\n'% (write_line, write_line1))

foo()

file as variable name is bad odea, and truncate call does not make sense, but what is your question?

i wanted to move this into code snippet actually

truncate call is done so that only file gets generated at different times, but yes, to keep a history, we have to remove it

as pyTony said, file as a variable name is bad because file as a name is used inside Python do denote i/o file stream objects.

truncate shortens existing file, you are creating a new file at 19 (which you do not close, but Python is very forgiving in this aspect) Do you want to make corrections and then post it as code snippet. After couple of posts more you are able to select Code Snippet type by yourself to a finalized version in a new article (thread).

"as pyTony said, file as a variable name is bad because file as a name is used inside Python do denote i/o file stream objects."

do i need to hard code the file name?

No but use a name which is not used for some built in functionality, or you loose the visibility of the original functionality and confuse the others reading your code (and sooner or later yourself). You could consider to return the file header block from function instead of writing it to file in function and I would not say that foo is most describtive also for what it does (and neither the Python documentation version spam).

The standard library contains the method getpass.getuser() to get the user name, and there is also os.path.expanduser('~') to get the home folder. On my unix system, there is no USERPROFILE environment variable for example.

Thanks for the information. I will modify this program.

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.