问题描述
我在这里看到许多类似问题的答案,但由于我的 Python 技能初露端倪,我似乎还不能完全适应它。我想节省单独抓取包含我需要在 R 中进行分析的数据集的时间,但我的脚本要么无法运行,要么似乎可以满足我的需求。
我需要 1) 遍历父文件夹中的大量子文件夹,2) 遍历这些子文件夹中的 bagillion .csv 文件并挑选出重要的 1(匹配下面的文本)和 3) 将其复制到一个新的干净文件夹,里面只有我想要的东西。
我尝试过的:
1)
import os,shutil,glob
src_fldr = 'C:/project_folder_withsubfolders';
dst_fldr = 'C:/project_folder_withsubfolders/subfolder_to_dump_into';
try:
os.makedirs(dst_fldr); ## it creates the destination folder
except:
print ("Folder already exist or some error");
for csv_file in glob.glob(src_fldr+'*statistics_Intensity_Sum_Ch=3_Img=1.csv*'):
shutil.copy2(csv_file,dst_fldr);
其中文本 statistics_Intensity_Sum 等是我复制文件所需的确切模式
- 这实际上并没有复制任何东西
srcDir = 'C:/project_folder_withsubfolders'
dstDir = 'C:/project_folder_withsubfolders/subfolder_to_dump_into'
def moveAllFilesinDir(srcDir,dstDir):
files = os.listdir(srcDir)
for f in files:
if f.find("statistics_Intensity_Sum_Ch=3_Img=1"):
shutil.move(f,dstDir)
else:
shutil.move(f,srcDir)
moveAlllFilesinDir(srcDir,dstDir)
- 这返回了以下错误:
File "C:\Users\jbla12\AppData\Local\Programs\Python\python39\lib\shutil.py",line 806,in move
os.rename(src,real_dst)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'F1 converted' -> 'C:/Users/jbla12/Desktop/R Analyses/p65_project/sum_files\\F1 converted'
那是因为这是我希望它通过的子文件夹!我尝试过其他方法,但在我的脚本中没有记录。
解决方法
已解决: 特别感谢“自动化无聊的东西”
import shutil
import os
dest = 'C:/Users/jbla12/Desktop/R Analyses/p65_project/sum_files/'
src = 'C:/Users/jbla12/Desktop/R Analyses/p65_project/'
txt_ID = 'statistics_Intensity_Sum_Ch=3_Img=1.csv'
def moveSpecFiles(txt_ID,src,dest):
#src is the original file(s) destination
#dest is the destination for the files to end up in
#spec_txt is what the files end with that you want to ID
for foldername,subfolders,filenames in os.walk(src):
for file in filenames:
if file.endswith(txt_ID):
shutil.copy(os.path.join(foldername,file),dest)
print('Your files are ready sir/madam!')
moveSpecFiles(txt_ID,dest)