-1

I have a Python code in which I am using useruser as my username:

zipfolder('shared-photo.zip', 'C:\Users\useruser\company\folder-images') 

How can I update this code to get the logged-in username?

For example this is what I tried:

myuser = os.popen("echo %username%").read().replace("\n","")

...and then when I print myuser, I get the right username:

print(myuser)

How can I use this variable in my code, instead of useruser?

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
john
  • 3
  • 1
  • `zipfolder('shared-photo.zip', 'C:\\Users\\{}\\company\\folder-images'.format(myuser))` – Itay Jul 09 '19 at 13:23

2 Answers2

1

You can concatenate your myuser variable to your string like this:

zipfolder("tgs-stealed", "C:\Users\\" + myuser + "\company\folder-images")

Or use str.format():

zipfolder("tgs-stealed", "C:\Users\{}\company\folder-images".format(myuser))

Also, as mentioned by @AbdulNiyasPM in the comments, you can use an f-string with Python 3.6+:

zipfolder("tgs-stealed", f"C:\Users\{myuser}\company\folder-images")
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
  • 1
    From python 3.6 onwards there is one more option available. **f-strings** – Abdul Niyas P M Jul 09 '19 at 13:25
  • thanks this code worked. but i have any more question. in my code the directory ziped and saved with name tgs-stealed.zip on my current directory. but i want save the zipped file on c:\shared-files folder. how can do this? please edit my code and show me. – john Jul 09 '19 at 13:40
  • @john This is a completely different issue, you should create a new question. – Ronan Boiteau Jul 09 '19 at 16:11
0

In Python have many forms. But to this string, you need prefix the string with r (to produce a raw string).

String concatenation:

zipfolder('shared-photo.zip', r'C:\Users\\' + str(myuser) + '\company\folder-images')

Conversion Specifier:

zipfolder('shared-photo.zip', r'C:\Users\\%s\company\folder-images' % myuser)

Using local variable names:

zipfolder('shared-photo.zip', r'C:\Users\\%(myuser)s\company\folder-images' % locals())

Using str.format():

zipfolder('shared-photo.zip', r'C:\Users\\{0}\company\folder-images'.format(myuser))

Using f-strings:

zipfolder('shared-photo.zip', r'C:\Users\\{myuser}\company\folder-images')) # added in Python 3.6

Adapted from 1.

Newton José
  • 441
  • 4
  • 9