0

What I'm trying to accomplish is to have my program move itself from the folder it's currently in, to another folder. In this case, Videos. This is the code:

import getpass
import os

userid = getpass.getuser()


print os.getcwd()

os.rename("$s/userid.py", "%s/Videos/userid.py")  % ('os.getcwd()', '%userid')

But running it from power shell gets me this error:

Traceback (most recent call last):
File "userid.py", line 9, in <module>
os.rename("$s/userid.py", "%s/Videos/userid.py")  % ('os.getcwd
WindowsError: [Error 3] The system cannot find the path specified

And then I thought maybe the parentheses with os.getcwd() was causing problems so I tried this but with the same error:

import getpass
import os
import shutil

userid = getpass.getuser()


currentpath = os.getcwd()

shutil.move("%s/userid.py", "C:/users/%s/Videos/userid.py")  % (currentpath, userid)

Also, if I don't just want the current user's id, but the id for all users profile, how would I do that?

Thanks

UPDATED: It works! Thanks so much everyone

import getpass
import os
import shutil


currentpath = os.path.abspath(os.path.dirname(__file__))


shutil.copyfile("%s/userid.py" % currentpath, "%s/Videos/userid.py" % os.path.expanduser('~'))
Joe
  • 3
  • 4
  • Ah I see. I changed it to "C:/users/%s/Videos/userid.py" and it still does not work though. – Joe Oct 16 '15 at 21:02
  • But you probably want to copy the file using `shutil.copyfile` instead of moving it; probably want to reference the file path as `os.path.abspath(os.path.dirname(__file__))` instead of using `os.getcwd()`, which depends on the working directory at program startup; should use `os.path.expanduser('~')` to get a user's home directory instead of assuming it's `C:\Users\username`, but you should actually use the Windows function [`SHGetKnownFolderPath`](https://msdn.microsoft.com/en-us/library/bb762188) to get the location of special folder, since a user can relocate it. – Eryk Sun Oct 16 '15 at 21:16
  • Just changed it, but it still does not work. Same error. – Joe Oct 16 '15 at 21:17
  • The modulo operartor (`%`) is overloaded for strings. It would have to be `"%s/userid.py" % currentpath` and `"C:/users/%s/Videos/userid.py" % userid`. But these are still wrong for all the reasons I mentioned above. – Eryk Sun Oct 16 '15 at 21:30
  • Ah, changed it according to your advice. It says no such path as %s/userid.py. Updated code in question – Joe Oct 16 '15 at 21:35
  • Python doesn't (currently) execute code in strings, and the modulo is a binary operation between the *string* and the value/tuple. It's `shutil.copyfile("%s/userid.py" % currentpath, "%s/Videos/userid.py" % os.path.expanduser('~'))`. – Eryk Sun Oct 16 '15 at 21:42
  • Ah! I understand now! And wow it works :D Thank you for helping me solve the problem and more importantly, learn the why and how! – Joe Oct 16 '15 at 21:45
  • It's still wrong since it assumes the "Videos" directory is in the default location, but the user may have relocated this directory. You need to use `SHGetKnownFolderPath`. – Eryk Sun Oct 16 '15 at 21:54
  • Specifically, I'm moving a file to start up like this: "shutil.copyfile("%s/userid.py" % currentpath, "%s/Start Menu/Programs/Startup/userid.py" % os.path.expanduser('~'))" I should use SHGetKnownFolderPath in this case as well? – Joe Oct 16 '15 at 22:05
  • You should use it especially in this case. Note that the start menu is defined in a subdirectory of the user's hidden `AppData\Roaming` directory. Don't assume the location of this folder. Use `FOLDERID_Startup` for the current user and `FOLDERID_CommonStartup` for all users. I'll add an answer, since using this requires ctypes and may be beyond your current skill set. – Eryk Sun Oct 16 '15 at 22:23
  • Which OS version are you targeting? `SHGetKnownFolderPath` is for Windows Vista+. Microsoft no longer supports Windows XP, but a lot of programs still have to support it. – Eryk Sun Oct 16 '15 at 22:35
  • Windows 8 and possibly windows 10 but 8 is the main focus for now. – Joe Oct 16 '15 at 22:42

2 Answers2

2

The location of special folders can be queried by calling SHGetKnownFolderPath with a KNOWNFOLDERID constant. This function was introduced in Windows Vista.

The following module defines the helper function get_known_folder_path as well as several of the commonly used KNOWNFOLDERID constants. If PyWin32 is installed, it also defines get_known_folder_id_list and list_known_folder, which allows listing virtual folders such as the apps folder.

knownfolders.py:

import ctypes
from ctypes import wintypes

__all__ = ['FOLDERID', 'get_known_folder_path']

_ole32 = ctypes.OleDLL('ole32')
_shell32 = ctypes.OleDLL('shell32')

class GUID(ctypes.Structure):
    _fields_ = (('Data1', ctypes.c_ulong),
                ('Data2', ctypes.c_ushort),
                ('Data3', ctypes.c_ushort),
                ('Data4', ctypes.c_char * 8))
    def __init__(self, guid_string):
        _ole32.IIDFromString(guid_string, ctypes.byref(self))

REFKNOWNFOLDERID = LPIID = ctypes.POINTER(GUID)

_ole32.IIDFromString.argtypes = (
    wintypes.LPCWSTR, # lpsz,
    LPIID)            # lpiid

_ole32.CoTaskMemFree.restype = None
_ole32.CoTaskMemFree.argtypes = (wintypes.LPVOID,)

_shell32.SHGetKnownFolderPath.argtypes = (
    REFKNOWNFOLDERID, # rfid
    wintypes.DWORD,   # dwFlags
    wintypes.HANDLE,  # hToken
    ctypes.POINTER(wintypes.LPWSTR)) # ppszPath

def get_known_folder_path(folder_id, htoken=None):
    pszPath = wintypes.LPWSTR()
    _shell32.SHGetKnownFolderPath(ctypes.byref(folder_id),
                                  0, htoken, ctypes.byref(pszPath))
    folder_path = pszPath.value
    _ole32.CoTaskMemFree(pszPath)
    return folder_path

try:
    from win32com.shell import shell, shellcon
except ImportError:
    pass
else:
    __all__ += ['get_known_folder_id_list', 'list_known_folder']

    PPITEMIDLIST = ctypes.POINTER(ctypes.c_void_p)

    _shell32.SHGetKnownFolderIDList.argtypes = (
        REFKNOWNFOLDERID, # rfid
        wintypes.DWORD,   # dwFlags
        wintypes.HANDLE,  # hToken
        PPITEMIDLIST)     # ppidl

    def get_known_folder_id_list(folder_id, htoken=None):
        pidl = ctypes.c_void_p()
        _shell32.SHGetKnownFolderIDList(ctypes.byref(folder_id),
                                        0, htoken, ctypes.byref(pidl))
        folder_id_list = shell.AddressAsPIDL(pidl.value)
        _ole32.CoTaskMemFree(pidl)
        return folder_id_list

    def list_known_folder(folder_id, htoken=None):
        result = []
        pidl = get_known_folder_id_list(folder_id, htoken)
        shell_item = shell.SHCreateShellItem(None, None, pidl)
        shell_enum = shell_item.BindToHandler(None, shell.BHID_EnumItems,
            shell.IID_IEnumShellItems)
        for item in shell_enum:
            result.append(item.GetDisplayName(shellcon.SIGDN_NORMALDISPLAY))
        result.sort(key=lambda x: x.upper())
        return result

# KNOWNFOLDERID
# https://msdn.microsoft.com/en-us/library/dd378457

# fixed
FOLDERID_Windows         = GUID('{F38BF404-1D43-42F2-9305-67DE0B28FC23}')
FOLDERID_System          = GUID('{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}')
FOLDERID_SystemX86       = GUID('{D65231B0-B2F1-4857-A4CE-A8E7C6EA7D27}')
FOLDERID_Fonts           = GUID('{FD228CB7-AE11-4AE3-864C-16F3910AB8FE}')
FOLDERID_ResourceDir     = GUID('{8AD10C31-2ADB-4296-A8F7-E4701232C972}')
FOLDERID_UserProfiles    = GUID('{0762D272-C50A-4BB0-A382-697DCD729B80}')
FOLDERID_Profile         = GUID('{5E6C858F-0E22-4760-9AFE-EA3317B67173}')
FOLDERID_Public          = GUID('{DFDF76A2-C82A-4D63-906A-5644AC457385}')
FOLDERID_ProgramData     = GUID('{62AB5D82-FDC1-4DC3-A9DD-070D1D495D97}')
FOLDERID_ProgramFiles    = GUID('{905e63b6-c1bf-494e-b29c-65b732d3d21a}')
FOLDERID_ProgramFilesX64 = GUID('{6D809377-6AF0-444b-8957-A3773F02200E}')
FOLDERID_ProgramFilesX86 = GUID('{7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E}')
FOLDERID_ProgramFilesCommon    = GUID('{F7F1ED05-9F6D-47A2-AAAE-29D317C6F066}')
FOLDERID_ProgramFilesCommonX64 = GUID('{6365D5A7-0F0D-45E5-87F6-0DA56B6A4F7D}')
FOLDERID_ProgramFilesCommonX86 = GUID('{DE974D24-D9C6-4D3E-BF91-F4455120B917}')

# common
FOLDERID_PublicDesktop   = GUID('{C4AA340D-F20F-4863-AFEF-F87EF2E6BA25}')
FOLDERID_PublicDocuments = GUID('{ED4824AF-DCE4-45A8-81E2-FC7965083634}')
FOLDERID_PublicDownloads = GUID('{3D644C9B-1FB8-4f30-9B45-F670235F79C0}')
FOLDERID_PublicMusic     = GUID('{3214FAB5-9757-4298-BB61-92A9DEAA44FF}')
FOLDERID_PublicPictures  = GUID('{B6EBFB86-6907-413C-9AF7-4FC2ABF07CC5}')
FOLDERID_PublicVideos    = GUID('{2400183A-6185-49FB-A2D8-4A392A602BA3}')
FOLDERID_CommonStartMenu = GUID('{A4115719-D62E-491D-AA7C-E74B8BE3B067}')
FOLDERID_CommonPrograms  = GUID('{0139D44E-6AFE-49F2-8690-3DAFCAE6FFB8}')
FOLDERID_CommonStartup   = GUID('{82A5EA35-D9CD-47C5-9629-E15D2F714E6E}')
FOLDERID_CommonTemplates = GUID('{B94237E7-57AC-4347-9151-B08C6C32D1F7}')

# peruser
FOLDERID_Desktop          = GUID('{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}')
FOLDERID_Documents        = GUID('{FDD39AD0-238F-46AF-ADB4-6C85480369C7}')
FOLDERID_Downloads        = GUID('{374DE290-123F-4565-9164-39C4925E467B}')
FOLDERID_Music            = GUID('{4BD8D571-6D19-48D3-BE97-422220080E43}')
FOLDERID_Pictures         = GUID('{33E28130-4E1E-4676-835A-98395C3BC3BB}')
FOLDERID_Videos           = GUID('{18989B1D-99B5-455B-841C-AB7C74E4DDFC}')
FOLDERID_LocalAppData     = GUID('{F1B32785-6FBA-4FCF-9D55-7B8E7F157091}')
FOLDERID_LocalAppDataLow  = GUID('{A520A1A4-1780-4FF6-BD18-167343C5AF16}')
FOLDERID_RoamingAppData   = GUID('{3EB685DB-65F9-4CF6-A03A-E3EF65729F3D}')
FOLDERID_StartMenu        = GUID('{625B53C3-AB48-4EC1-BA1F-A1EF4146FC19}')
FOLDERID_Programs         = GUID('{A77F5D77-2E2B-44C3-A6A2-ABA601054A51}')
FOLDERID_Startup          = GUID('{B97D20BB-F46A-4C97-BA10-5E3608430854}')
FOLDERID_Templates        = GUID('{A63293E8-664E-48DB-A079-DF759E0509F7}')
FOLDERID_UserProgramFiles = GUID('{5CD7AEE2-2219-4A67-B85D-6C9CE15660CB}')

# virtual
FOLDERID_AppsFolder       = GUID('{1e87508d-89c2-42f0-8a7e-645a0f50ca58}')

# win32com defines most of these, except the ones added in Windows 8.
FOLDERID_AccountPictures  = GUID('{008ca0b1-55b4-4c56-b8a8-4de4b299d3be}')
FOLDERID_CameraRoll       = GUID('{AB5FB87B-7CE2-4F83-915D-550846C9537B}')
FOLDERID_PublicUserTiles  = GUID('{0482af6c-08f1-4c34-8c90-e17ec98b1e17}')
FOLDERID_RoamedTileImages = GUID('{AAA8D5A5-F1D6-4259-BAA8-78E7EF60835E}')
FOLDERID_RoamingTiles     = GUID('{00BCFC5A-ED94-4e48-96A1-3F6217F21990}')
FOLDERID_Screenshots      = GUID('{b7bede81-df94-4682-a7d8-57a52620b86f}')
FOLDERID_SearchHistory    = GUID('{0D4C3DB6-03A3-462F-A0E6-08924C41B5D4}')
FOLDERID_SearchTemplates  = GUID('{7E636BFE-DFA9-4D5E-B456-D7B39851D8A9}')
FOLDERID_ApplicationShortcuts = GUID('{A3918781-E5F2-4890-B3D9-A7E54332328C}')
FOLDERID_HomeGroupCurrentUser = GUID('{9B74B6A3-0DFD-4f11-9E78-5F7800F2E772}')
FOLDERID_SkyDrive             = GUID('{A52BBA46-E9E1-435f-B3D9-28DAA648C0F6}')
FOLDERID_SkyDriveCameraRoll   = GUID('{767E6811-49CB-4273-87C2-20F355E1085B}')
FOLDERID_SkyDriveDocuments    = GUID('{24D89E24-2F19-4534-9DDE-6A6671FBB8FE}')
FOLDERID_SkyDrivePictures     = GUID('{339719B5-8C47-4894-94C2-D8F77ADD44A6}')

class SimpleNamespace(object):
    def __init__(self, **kwds):
        vars(self).update(kwds)
    def __dir__(self):
        return [x for x in sorted(vars(self)) if not x.startswith('__')]

FOLDERID = SimpleNamespace(
    # fixed
    Windows = FOLDERID_Windows,
    System = FOLDERID_System,
    SystemX86 = FOLDERID_SystemX86,
    Fonts = FOLDERID_Fonts,
    ResourceDir = FOLDERID_ResourceDir,
    UserProfiles = FOLDERID_UserProfiles,
    Profile = FOLDERID_Profile,
    Public = FOLDERID_Public,
    ProgramData = FOLDERID_ProgramData,
    ProgramFiles = FOLDERID_ProgramFiles,
    ProgramFilesX64 = FOLDERID_ProgramFilesX64,
    ProgramFilesX86 = FOLDERID_ProgramFilesX86,
    ProgramFilesCommon = FOLDERID_ProgramFilesCommon,
    ProgramFilesCommonX64 = FOLDERID_ProgramFilesCommonX64,
    ProgramFilesCommonX86 = FOLDERID_ProgramFilesCommonX86,
    # common
    PublicDesktop=FOLDERID_PublicDesktop,
    PublicDocuments=FOLDERID_PublicDocuments,
    PublicDownloads=FOLDERID_PublicDownloads,
    PublicMusic=FOLDERID_PublicMusic,
    PublicPictures=FOLDERID_PublicPictures,
    PublicVideos=FOLDERID_PublicVideos,
    CommonStartMenu=FOLDERID_CommonStartMenu,
    CommonPrograms=FOLDERID_CommonPrograms,
    CommonStartup=FOLDERID_CommonStartup,
    CommonTemplates=FOLDERID_CommonTemplates,
    # user
    Desktop=FOLDERID_Desktop,
    Documents=FOLDERID_Documents,
    Downloads=FOLDERID_Downloads,
    Music=FOLDERID_Music,
    Pictures=FOLDERID_Pictures,
    Videos=FOLDERID_Videos,
    LocalAppData=FOLDERID_LocalAppData,
    LocalAppDataLow=FOLDERID_LocalAppDataLow,
    RoamingAppData=FOLDERID_RoamingAppData,
    StartMenu=FOLDERID_StartMenu,
    Programs=FOLDERID_Programs,
    Startup=FOLDERID_Startup,
    Templates=FOLDERID_Templates,
    UserProgramFiles=FOLDERID_UserProgramFiles,
    # virtual
    AppsFolder=FOLDERID_AppsFolder,
    AccountPictures=FOLDERID_AccountPictures,
    CameraRoll=FOLDERID_CameraRoll,
    PublicUserTiles=FOLDERID_PublicUserTiles,
    RoamedTileImages=FOLDERID_RoamedTileImages,
    RoamingTiles=FOLDERID_RoamingTiles,
    Screenshots=FOLDERID_Screenshots,
    SearchHistory=FOLDERID_SearchHistory,
    SearchTemplates=FOLDERID_SearchTemplates,
    ApplicationShortcuts=FOLDERID_ApplicationShortcuts,
    HomeGroupCurrentUser=FOLDERID_HomeGroupCurrentUser,
    SkyDrive=FOLDERID_SkyDrive,
    SkyDriveCameraRoll=FOLDERID_SkyDriveCameraRoll,
    SkyDriveDocuments=FOLDERID_SkyDriveDocuments,
    SkyDrivePictures=FOLDERID_SkyDrivePictures,
)

if __name__ == '__main__':
    for fid in dir(FOLDERID):
        try:
            path = get_known_folder_path(getattr(FOLDERID, fid))
            print("%s = %s" % (fid, path))
        except OSError:
            pass

Example:

import os
import shutil
from knownfolders import *

all_users = True

filename = 'userid.py'
module_path = os.path.abspath(os.path.dirname(__file__))

if all_users:
    startup_path = get_known_folder_path(FOLDERID.CommonStartup)
else:
    startup_path = get_known_folder_path(FOLDERID.Startup)

src = os.path.join(module_path, filename)
dst = os.path.join(startup_path, filename)

shutil.copyfile(src, dst)
Eryk Sun
  • 33,190
  • 5
  • 92
  • 111
  • Thanks! I see now. The whole thing is a tad complex but I get the gist. I did some more research and it looks like adding the program to the startup folder isn't the best way to have it start on startup. I should add it to a startup registry? I found this which I'm not sure if it's the right thing or not: import _winreg, webbrowser key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,'Software\Microsoft\Windows\CurrentVersion\Run',_winreg.KEY_SET_VALUE) _winreg.SetValueEx(key,'pytest',0,_winreg.REG_BINARY,'%s' %currentpath) key.Close() Sorry about the formatting, not sure how – Joe Oct 17 '15 at 01:38
  • Ah ok. Well, I see many warnings on modifying the registry so I'll stick to what you've shown me. So, I have to use both pieces of code you showed or just the second one? It looks like the first is just to show me how it works and how the folders each have a unique ID. I put the second piece of code in and it doesn't seem to work, the rest of the code doesn't even run. – Joe Oct 17 '15 at 02:00
  • As I wrote the example, the knownfolders module has to be located in a `sys.path` directory to be imported (i.e. the line `from knownfolders import *`) . Are you creating a package, i.e. do you have an `__init__.py` in the directory? – Eryk Sun Oct 17 '15 at 02:05
  • Ah no I don't. I intent to compile the program to an exe file so I doubt other users are going to as well. – Joe Oct 17 '15 at 02:09
  • Am I able to somehow just import the knownfolders module without it being located in a sys.path directory? – Joe Oct 17 '15 at 02:16
  • If this is a script, just save knownfolders.py in the same directory as the script. Python adds the main script's directory to `sys.path`. – Eryk Sun Oct 17 '15 at 02:24
  • If you run knownfolders.py itself as the main script, it should print out all of the defined folder paths. – Eryk Sun Oct 17 '15 at 02:26
  • FYI, `from knownfolders import *` is importing the names listed in `knownfolders.__all__`, i.e. the `get_known_folder_path` function and the `FOLDERID` namespace that has the `KNOWNFOLDERID` constants. – Eryk Sun Oct 17 '15 at 02:29
  • So I put knownfolders.py and userid.py in the same directory for this to work but when I run userid.py, all it does is create a "knownfolders.pyc" file in that directory and nothing else happens. Opening knownfolders.pyc is just a bunch of random characters. – Joe Oct 17 '15 at 02:30
  • I don't know what userid.py is. I know it's the file you're trying to copy. knownfolders.py has to be on `sys.path`, which could be the same directory as the script that *uses* it (i.e. actually imports it and uses `get_known_folder_path` function) or if that's not convenient add it to another directory that's on `sys.path`. Or just dump it all in the same file (without the `if __name__ == '__main__'` test code, of course) if you can't figure out how to manage `sys.path`. – Eryk Sun Oct 17 '15 at 02:34
  • Ok, I think the problem is that I'm not sure how to add a module to sys.path since I'm not too sure what sys.path is. A search tells me it's where Python looks for modules (which is why knownfolders.py has to be there). I had put both userid.py and knownfolders.py in Documents. But I can't find out how to add it. Someone said I can't add files to it, only a directory containing a file? – Joe Oct 17 '15 at 02:41
  • You say you plan to freeze this as an exe. So don't do anything special for now. Just move knownfolders.py to the `Lib\site-packages` directory of your Python installation. – Eryk Sun Oct 17 '15 at 03:00
  • I found /python27/lib/site-packages and added the knownfolders.py there but that doesn't do anything except create a knownfolders.pyc in that folder. – Joe Oct 17 '15 at 03:00
  • A .pyc file is compiled bytecode. It gets cached when a module is imported, so the next run it doesn't have to be compiled again. To use the module just do `from knownfolders import *;` `startup_path = get_known_folder_path(FOLDERID.CommonStartup)`. – Eryk Sun Oct 17 '15 at 03:03
  • Where does "startup_path = get_known_folder_path(FOLDERID.CommonStartup)" go? I tried it with it on the same line, the next line, and the next line indented but none do anything. – Joe Oct 17 '15 at 03:10
  • What do you mean by "none do anything"? It should store the path of the startup directory in `startup_path`. You can do `print startup_path` if you want to see the value. – Eryk Sun Oct 17 '15 at 03:27
  • Ok so I put in this to userid.py: from knownfolders import *; startup_path = get_known_folder_path(FOLDERID.CommonStartup) and when I try to run userid.py, nothing happens at all. Should it all be on one line? knownfolders.py and knownfolders.pyc are both in Lib/site-packages. Running from powershell it says the errors: File "userid.py", line 19, in shutil.copyfile(src, dst) File "C:\Python27\lib\shutil.py", line 83, in copyfile with open(dst, 'wb') as fdst: – Joe Oct 17 '15 at 03:32
  • Please link to userid.py (e.g. post it on pastebin.com), so I can take a look at what you're trying to do. – Eryk Sun Oct 17 '15 at 04:18
  • OK, that's just my code plus a `MessageBoxA` call. Though in your paste you're missing the opening quote before userid.py in `filename = 'userid.py'`. Remove `; startup_path = get_known_folder_path(FOLDERID.CommonStartup)`. That's defined later. Use `all_users = False` if you want it to be copied to the current user's startup folder. – Eryk Sun Oct 17 '15 at 04:29
  • I fixed that quote issue, that wasn't actually in the code when testing it but I accidentally deleted it when pasting it. And changing True to False works! Any reason why having it True causes it to fail? – Joe Oct 17 '15 at 04:38
  • If your script isn't elevated (run as administrator), then it only has read access to the common startup folder. Only administrators can add files there. – Eryk Sun Oct 17 '15 at 04:43
  • Ah of course, that was obvious lol. So if this is an exe and all_users = True, then it will ask for permission or will it just not run? I ask because running the .py file will not ask for permission. It will just do nothing. – Joe Oct 17 '15 at 04:47
  • If you want to use the common startup folder for an exe, it needs an embedded manifest that requests elevation. py2exe can set this up. – Eryk Sun Oct 17 '15 at 04:52
  • Python's installer doesn't add a `runas` key to the `Python.File` type, so right-clicking a .py file doesn't give an option to "run as administrator". But you can run the script from an elevated command prompt. – Eryk Sun Oct 17 '15 at 04:53
  • Ok thanks! I appreciate all the help in understanding this. I feel like this answer and these comments will be priceless to someone else trying to find out the same thing lol – Joe Oct 17 '15 at 04:53
0
os.rename("$s/userid.py", "%s/Videos/userid.py")  % ('os.getcwd()', '%userid')

%userid will only give you userid, you need to specify the full path. Also note $s you have used, it should instead be %s.

Please note both the directories should exist beforehand. While the file in the destination directory shouldn't.

Also you can use the shutil.move() for the same.

garg10may
  • 5,794
  • 11
  • 50
  • 91
  • Just changed it and updated coded in the question. Using shutil.move and fixed other problems. Now error says File "userid.py", line 10, in shutil.move("%s/userid.py", "C:/users/%s/Videos/userid.py") % (currentpath, currentuser) File "C:\Python27\lib\shutil.py", line 302, in move copy2(src, real_dst) File "C:\Python27\lib\shutil.py", line 130, in copy2 copyfile(src, dst) File "C:\Python27\lib\shutil.py", line 82, in copyfile with open(src, 'rb') as fsrc: IOError: [Errno 2] No such file or directory: '%s/userid.py' – Joe Oct 16 '15 at 21:23
  • Give full paths in os.rename without any fancy formatting and try. – garg10may Oct 16 '15 at 21:25
  • How do I give the full path without the formatting? I don't know the path. – Joe Oct 16 '15 at 21:26
  • how can you move a file without knowing the path. The `os.getcwd()` will actually give you your interpretor path. If you know the path on windows go to the search bar and click, it will give you the full path. Copy and use it. – garg10may Oct 16 '15 at 21:29
  • Yes but the path will be different for someone else. for me, let's say it's "C:/bob/downloads" and I want to move it to "C:/bob/Videos". The other person will not have a name of bob so it won't work. – Joe Oct 16 '15 at 21:32
  • Or if you are sure that it's at the user directory use. C:\Users\ and then `getpass.getuser()` but make source path and destination path in separate string and then use it in os.rename. Your formatting is all the way incorrect. Also remember – garg10may Oct 16 '15 at 21:32
  • `os.rename()` work won't if files are on different disks. In that case use `shutil.move()` – garg10may Oct 16 '15 at 21:33