Save file path without specifying User

108 Views Asked by At

Currently, this code works. It creates a text file named SerialNumber that saves in pictures. The problem is I can't seem to work out how to get it to work on any computer. So for example, if I remove \users\Jarvis from the file path it no longer finds its way to pictures. I'm trying to get it to work no matter who is logged in.

import os


Save_Path='C:\\Users\\Jarvis\\Pictures\\SerialNumber.txt'

with open(Save_Path, 'w') as f:
    f.write(str(os.system('start cmd /k "wmic bios get serialnumber >C:\\Users\\Jarvis\\Pictures\\SerialNumber.txt"')))

I've tried to set it as: \users\Admin \users%UserProfile%
\users\user but that returns FileNotFoundError: [Errno 2] No such file or directory:


import os
from pathlib import Path

Save_Path= 'C:\\Users\\Pictures\\SerialNumber.txt'

path = Path.home() / "Pictures\SerialNumber.txt"

with open(path, 'w') as f:
    f.write(str(os.system('start cmd /k "wmic bios get serialnumber >C:\\Users\\%UserProfile%\\Pictures\\SerialNumber.txt"')))

With Subprocess and replace I was able to print to python just the serial number

import subprocess
SerialNumber = 'wmic bios get serialnumber'
result = subprocess.getoutput(SerialNumber)
print(result.replace("SerialNumber", ""))
1

There are 1 best solutions below

0
AudioBubble On

Okay after some help, and research, This is the final code. It uses a subprocess that will output to python>CMD. I then used re (lines 7 and 8) to .strip and re.sub removing everything that wasn't actually the serial number. I installed pyperclip to copy

import subprocess
import pyperclip
import re
import os

SerialNumber = 'wmic bios get serialnumber'
result = subprocess.getoutput(SerialNumber)
SerialResult = (result.strip("SerialNumber"))
print(re.sub("[^a-zA-Z0-9]+", "", SerialResult))
pyperclip.copy(re.sub("[^a-zA-Z0-9]+", "", SerialResult))