我正在尝试复制Windows用户配置文件下的Documents文件夹,shutil.copytree(documents, destination)
部分起作用。它将文档复制到目标的根目录(在本例中为R:
驱动器),并且还将尝试复制其他Windows特殊文件夹(“我的音乐”,“我的图片”等),即使它们不存在于“文档”下。
import shutil
def main():
try:
user_profile = os.getenv("USERPROFILE")
# Construct a full path to the documents folder
documents = Path(user_profile).joinpath("Documents")
# Destination for the Documents folder
destination = Path("R:\\Test")
shutil.copytree(documents, destination)
except (FileNotFoundError, shutil.Error) as error:
print(error)
if __name__ == '__main__':
main()
这是抛出的异常的摘录:
[('C:\\Users\\ConsoleGeek\\Documents\\My Music', 'R:\\Test\\My Music',
"[WinError 5] Access is denied: 'C:\\\\Users\\\\ConsoleGeek\\\\Documents\\\\My Music'")
...
这些文件夹都不存在于“文档”下,所以我不完全理解为什么shutil
试图复制这些特殊文件夹。如果我尝试在用户配置文件下复制常规文件夹,则可以使用。
shutil.copytree(documents, destination, symlinks=True)
如果这些“特殊文件夹”是符号链接(或Windows的等效符号链接)。
使用cmd.exe:
如果打开Documents
并将目录更改为cmd.exe
,我们可以运行Documents
查看所有文件夹(包括隐藏的文件夹)。
dir /A:H /B
使用Powershell] ::
如果打开dir /A:H /B
并键入C:\Users\ConsoleGeek\Documents>dir /A:H /B
desktop.ini
My Music
My Pictures
My Videos
,它将列出powershell.exe
文件夹中的所有项目。
注
:不显示特殊文件夹。Get-ChildItem -Force -File -Path .\Documents\
使用Python:
我在VSCode中运行了以下代码:
Get-ChildItem -Force -File -Path .\Documents\
使用文件浏览器:
如果选择显示隐藏文件的选项,则Documents
文件夹仍为空。
递归复制
:使用cmd.exe
:使用PS C:\Users\ConsoleGeek> Get-ChildItem -Force -File -Path .\Documents\
Directory: C:\Users\ConsoleGeek\Documents
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a-hs- 10/4/2019 6:00 PM 402 desktop.ini
命令和def main():
try:
user_profile = os.getenv("USERPROFILE")
documents = Path(user_profile).joinpath("Documents")
for item in documents.iterdir():
print(item)
except (FileNotFoundError, shutil.Error) as error:
print(error)
if __name__ == '__main__':
main()
# Output:
C:\Users\ConsoleGeek\Documents\desktop.ini
C:\Users\ConsoleGeek\Documents\My Music
C:\Users\ConsoleGeek\Documents\My Pictures
C:\Users\ConsoleGeek\Documents\My Videos
Documents
开关,我们可以复制所有的每个文件夹/文件,包括空的和隐藏的。
xcopy
/E
具有误导性,因为当启用“显示隐藏的文件时,您无法验证没有复制任何内容。”>
使用Powershell] ::
与/H
开关一起使用C:\Users\ConsoleGeek>xcopy Documents R:\Sync\Documents /E /H
Documents\desktop.ini
Access denied
Unable to create directory - R:\Sync\Documents\My Music
1 File(s) copied
cmdlet,我们得到了拒绝访问错误,类似于1 File(s) copied
。
Copy-Item
解决方案::使用cmd.exe
-Recurse
具有cmd.exe
参数。您为文件提供了要排除的文件夹/文件名。
Copy-Item : Access to the path 'C:\Users\ConsoleGeek\Documents\My Music' is denied.
并与xcopy
命令一起使用:
/Exclude:filename.txt
使用Powershell] ::
My Music My Pictures My Video desktop.ini
参数无法与xcopy
参数一起使用,因此它将仅复制空的My Music,My ...文件夹。要从复制中排除它们,可以为C:\Users\ConsoleGeek>xcopy Documents R:\Sync\Documents /E /H /EXCLUDE:filenames.txt
参数提供通配符。-Exclude
[如果需要复制子目录,但要排除某些子目录,则可以构建您不想复制的目录列表,并循环浏览-Recurse
文件夹,并对照该列表检查每个项目。您可能需要进行试验,以了解适合您的要求。
使用Python
:根据要求,您的脚本显然会有所不同,但是您可以使用此功能过滤特殊文件夹和
-Exclude
文件。
Copy-Item -Path .\Documents\ -Destination "R:\Sync\Documents" -Exclude ("My*", ".ini")