Skip to content

Instantly share code, notes, and snippets.

@cwhy
Created October 24, 2015 10:59
Show Gist options
  • Save cwhy/2b99f9330b1d0fe881e6 to your computer and use it in GitHub Desktop.
Save cwhy/2b99f9330b1d0fe881e6 to your computer and use it in GitHub Desktop.
Example for Windows file operation using Python
import os
import glob
import errno
import pandas as pd
import subprocess as sp
si = sp.STARTUPINFO()
si.dwFlags |= sp.STARTF_USESHOWWINDOW
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
cwd = os.getcwd()
data_dir = os.path.abspath(os.path.join(cwd, os.pardir, 'data'))
dest_dir = os.path.abspath(
os.path.join(cwd, os.pardir, 'data_clean', 'data'))
dest_dir_dti = os.path.join(dest_dir, 'dti')
mkdir_p(dest_dir_dti)
subj_info = pd.read_csv(os.path.join(cwd, 'SubInfo.csv'))
NC_IDs = subj_info[subj_info.Group == 'NC']['Scan_ID']
subj_folder_names = next(os.walk(data_dir))[1] # find all folders
for sfn in subj_folder_names:
print(sfn)
scan_n = int(float(sfn.split(' ')[0]))
sn = sfn.split(' ')[1]
raw_path = os.path.join(data_dir, sfn, sn + '_DICOM')
if scan_n in NC_IDs:
dest_dir_fun = os.path.join(dest_dir_dti, 'NC', 'DTI')
dest_dir_t1 = os.path.join(dest_dir_dti, 'NC', 'T1Img')
else:
dest_dir_fun = os.path.join(dest_dir_dti, 'SCZ', 'DTI')
dest_dir_t1 = os.path.join(dest_dir_dti, 'SCZ', 'T1Img')
sub_id = subj_info[subj_info.Scan_ID == scan_n]['Sub_ID'].values[0]
mkdir_p(dest_dir_fun)
mkdir_p(dest_dir_t1)
fun_path = os.path.join(dest_dir_fun, sub_id)
t1_path = os.path.join(dest_dir_t1, sub_id)
mkdir_p(fun_path)
fun_files = glob.iglob(os.path.join(raw_path, 'x*DTI32*10??.*'))
for file_ in fun_files:
sp.call(['xcopy', file_, fun_path, '/Y'],
startupinfo=si)
mkdir_p(t1_path)
t1_files = glob.iglob(os.path.join(raw_path, '*DAX*10??.nii.gz'))
for file_ in t1_files:
sp.call(['xcopy', file_, t1_path, '/Y'],
startupinfo=si)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment