仅从根目录复制简单python文件

仅从根目录复制简单python文件,python,Python,我是python新手,正在尝试创建一个文件夹并在其中复制文件。我可以通过以下行成功创建文件夹并成功复制根目录中的另一个同级文件夹: #copy_tree("old-tocopy", "new_folder") # this works (因此旧tocopy文件夹和新_文件夹在根目录中是同级的) 但是,当使用tilder(~)符号导航到该目录时,我无法将文件从另一个目录复制到该目录中(尽管我可以在终端中以CD的形式进行导航:CD~/Documents/he

我是python新手,正在尝试创建一个文件夹并在其中复制文件。我可以通过以下行成功创建文件夹并成功复制根目录中的另一个同级文件夹:

#copy_tree("old-tocopy", "new_folder") # this works
(因此旧tocopy文件夹和新_文件夹在根目录中是同级的)

但是,当使用tilder(~)符号导航到该目录时,我无法将文件从另一个目录复制到该目录中(尽管我可以在终端中以CD的形式进行导航:
CD~/Documents/hello

为了更好地解释,我的MacBook上有以下文件夹:

~/Documents/hello
hello文件夹包含一个文件“hello.txt”、子文件夹“hi”和子文件夹“hi.txt”。但我得到了一个错误:

Traceback (most recent call last):
  File "backuper.py", line 10, in <module>
    copy_tree("~/Documents/hello", "new_folder")
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/distutils/dir_util.py", line 123, in copy_tree
    raise DistutilsFileError(
distutils.errors.DistutilsFileError: cannot copy tree '~/Documents/hello': not a directory

感谢您的帮助。

您不能将
~
与python一起使用,因为
cd~
是特定于您的bash(或其他)shell的,因为python
~
只是文字,因此
os.path.isdir(~/Documents/hello”)
给出了
False


你可以用一个完整的路径替换它,比如
/home/Documents/hello
,它会工作。

做了这个更改后,我仍然会遇到同样的错误。你能给我
os.path.isdir(“~/Documents/hello”)
print(os.path.isdir(“~/Documents/hello”))的输出吗?print(os.path.isdir(“~/Documents/hello/”)的输出是假的,print也是假的@user8758206我已更新我的答案您的逻辑正确-设法使用/Users/nick/Documents/hello使其正常工作。非常感谢。
import os
from distutils.dir_util import copy_tree

#1 - create new folder
if not os.path.exists('new_folder'):
    os.makedirs('new_folder')

#2 - copy files into new folder
#copy_tree("old-tocopy", "new_folder") # this works
copy_tree("~/Documents/hello", "new_folder")