[英]Is there a way to copy files from one folder to another using a subtext of that file name in python?
[英]Copy file with specific name from one folder to another in python
我正在嘗試將特定文件從一個文件夾復制到另一個文件夾,但出現錯誤,我不明白為什么:
import os
import shutil
def setPath_getData():
# Set up folders for data
newpath = r'userdata'
if not os.path.exists(newpath):
os.makedirs(newpath)
os.makedirs('userdata/sleep')
os.makedirs(r'userdata/distance')
os.makedirs(r'userdata/steps')
os.makedirs(r'userdata/lightly')
os.makedirs(r'userdata/mod')
os.makedirs(r'userdata/sedentary')
os.makedirs(r'userdata/very')
os.makedirs(r'userdata/heart-rate-zone')
os.makedirs(r'userdata/heart-rate')
# Get data from fitbit
filenames = os.listdir("user-site-export")
unique_filenames = set()
for f in filenames:
unique_filenames.add(f.split("-")[0])
source = os.listdir('user-site-export/')
dest = '/userdata/sleep/'
for file in source:
if file.startswith('sleep'):
shutil.copy(file, dest)
#ls userdata/
print("Data loaded successfully")
setPath_getData()
它給出的錯誤是:
FileNotFoundError: [Errno 2] No such file or directory: 'sleep-2020-01-09.json'
所以看起來它正在獲取正確的文件,但它沒有將它們復制到 dest。 任何想法為什么?
您必須在復制命令中的文件變量之前指定源路徑: shutil.copy(os.path.join("user-site-export", file), dest)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.