![](/img/trans.png)
[英]How do I copy files from one directory with sub-folders to another directory with sub-folders based on folder name?
[英]How do I copy files into folders based on the file containing the folder name?
的Python版本:2.7.13
操作系統:Windows
因此,我正在編寫一個腳本,根據要求將各種名稱的文件復制到一個特定的文件夾中,該要求是文件中必須包含文件夾名稱。 (我對此很陌生,只是嘗試創建腳本以提高工作效率-我查看了很多StackOverflow頁面和網絡上的某些地方,但找不到用於此特定任務的與Python相關的東西)
我已經將文件夾轉換成可以搜索文件名的字符串列表,但是當我將它們復制過來時,它們全部進入找到的第一個文件夾。 我需要幫助的確切部分是如何將文件復制到找到匹配字符串的文件夾中。
本質上是“如果有的話(目錄名中的x在列表中為x):”,“將文件移動到x”。
關於sourceFolder和destFolder,這些是從代碼前面的用戶輸入獲得的變量。 (sourceFolder包含文件,destFolder包含我要復制到的子文件夾)
編輯:我在destFolder中有多個子文件夾,如果它們與字符串匹配,我可以獲取要復制的文件(如果不存在匹配項,則不進行復制)。 但是,當它們確實進行復制時,它們都進入同一個子文件夾。
list=[]
if var == "y": #Checks for 'Yes' answer
for subdir, dirs, files in os.walk(destFolder):
subdirName = subdir[len(destFolder) + 1:] #Pulls subfolder names as strings
print subdirName
list.insert(0, subdirName)
print "Added to list"
for subdir, dirs, files in os.walk(sourceFolder):
for file in files:
dirName = os.path.splitext(file)[0] #This is the filename without the path
destination = "{0}\{1}".format(destFolder, subdirName)
string = dirName #this is the string we're looking in
if any(x in dirName for x in list):
print "Found string: " + dirName
shutil.copy2(os.path.join(subdir, file), destination)
else:
print "No String found in: " + dirName
編輯2:經過一些調整和外部幫助之后,就工作代碼而言,這就是我最終的目的(為了讓遇到此問題的任何人受益)。 一些變量更改了名稱,但希望該結構可讀。
從os導入shutil,os,re,stat從os.path導入listdir導入isfile,join
destKey = dict()
if var == "y": #Checks for 'Yes' answer
for root, dirs, files in os.walk(destFolder):
for dest_folder in dirs: #This is the folder, for each we look at
destKey[dest_folder] = os.path.join(root, dest_folder) #This is where we convert it to a dictionary with a key
for sourceFile in os.listdir(sourceFolder):
print ('Source File: {0}').format(sourceFile)
sourceFileName = os.path.basename(sourceFile) #filename, no path
for dest_folder_name in destKey.keys():
if dest_folder_name in sourceFileName.split('-'): #checks for dest name in sourceFile
destination = destKey[dest_folder_name]
print "Key match found for" + dest_folder_name
shutil.copy2(os.path.join(sourceFolder, sourceFile), destination)
print "Item copied: " + sourceFile
這就是我做比較的方式:
list = ["abc", "def", "ghi"]
dirname = "abcd"
for x in list:
if x in dirname:
print(dirname, x)
因此,您的代碼如下所示:
for subdir, dirs, files in os.walk(sourceFolder):
for file in files:
dirName = os.path.splitext(file)[0] #This is the filename without the path
destination = "{0}\{1}".format(destFolder, subdirName)
for x in list:
if x in dirName:
print "Found string: " + dirName
shutil.copy2(os.path.join(subdir, file), destination)
else:
print "No String found in: " + dirName
這樣可以解決問題嗎?
我試圖使它盡可能接近您的原始代碼。 我們將其中包含文件夾名稱的所有文件丟到相應的文件夾中。 我們不會使用設置的緩存遍歷所有目錄重復任何文件。
import os, shutil
dirs_ls = []
destFolder = 'Testing'
for subdir, dirs, files in os.walk(destFolder):
subdirName = subdir[len(destFolder) + 1:] # Pulls subfolder names as strings
dirs_ls.append(subdirName)
dirs_ls = filter(None, dirs_ls)
copied_files = set()
for subdir, dirs, files in os.walk(destFolder):
for file_name in files:
if file_name in copied_files:
continue
file_name_raw = file_name.split('.')[0]
for dir in dirs_ls:
if dir not in file_name_raw:
continue
shutil.copy2(os.path.join(destFolder, file_name), os.path.join(destFolder, file_name_raw))
copied_files.add(file_name)
腳本運行之前的目錄結構:
.
├── bro
├── bro.txt
├── foo
├── foo.txt
├── yo
└── yo.txt
腳本運行后的目錄結構:
.
├── bro
│ └── bro.txt
├── bro.txt
├── foo
│ └── foo.txt
├── foo.txt
├── yo
│ └── yo.txt
└── yo.txt
您的解決方案使用any()確定文件是否與任何子目錄匹配,然后將文件移至存儲在subdir
的最后一個值。 並注意subdirName在上一個循環中的最后設置方式,因此其值在第二個循環中將永遠不變。 我也看到了其他一些問題。 您需要一個子目錄名稱列表,但是還需要一個完整的相對路徑列表,假設destFolder和sourceFolder不相同,並且具有子目錄。 最好不要用您自己的變量名覆蓋諸如list
類的基本類型。 嘗試這個:
from os.path import dirname, join, splitext
from os import walk
dir_list = []
if var == "y": #Checks for 'Yes' answer
for subdir, dirs, files in walk(destFolder):
dir_list.append(subdir) # keeping the full path, not just the last directory
print 'Added "{0}" to the list'.format(subdir)
for subdir, dirs, files in walk(sourceFolder):
for file in files:
fname = splitext(file)[0] # This is the filename without the path
for dpath in dir_list:
# Fetch last directory in the path
dname = dirname(dpath)
if dname in fname:
# Directory name was found in the file name; copy the file
destination = join(destFolder, dpath, file)
shutil.copy2(join(subdir, file), destination)
我沒有測試上面的內容,但是應該可以使您了解如何進行此工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.