[python] 文件复制/路径检测
import shutil
shutil.copytree(sourceResDir, dstResDir)
复制目录,olddir和newdir都只能是目录,且newdir必须不存在
文件的拷贝用shutil.copyfile(srcFilePath,dstFilePath)
oldfile和newfile都只能是文件
shutil.copy( src, dst)
复制一个文件,到一个文件或一个目录
import os
if not os.path.exist(path)
检测文件夹是否存在os.mkdir()
如果不存在,创建文件夹 ,mkdir只能创建最后一层的文件夹os.path.exists(no_exist_file.txt)
判断文件,文件夹是否存在
import os
#os.walk(path)遍历文件夹,没有返回值,直接循环调用
for root, dirs, files in os.walk(".", topdown=False):
for name in files:
print(os.path.join(root, name)) #文件名
for name in dirs: # 子文件夹名
print(os.path.join(root, name))
csv
读取
with open(os.path.join('/hdd/NTU_RGBD', 'split_ntu_cs_frames.csv'), 'r') as fin:
reader = csv.reader(fin)
data = list(reader)
root_path = '/hdd/NTU_RGBD/cs_frames'
count = 0
for item in data:
print item
origin_path = os.path.join(root_path,item[0],item[1],item[3]+'_rgb-'+item[4].zfill(4)+'.jpg')
new_path = os.path.join('/hdd/NTU_RGBD/cs_one_frames',item[0],item[2],item[3]+'__rgb--00'+item[4]+'.jpg')
shutil.copy(origin_path,new_path)
count += 1
print count
写入
with open('split_ntu_cs_frames.csv', 'w') as fout:
writer = csv.writer(fout)
writer.writerows(frames)
write_row write_rows
dict
for train_sample in train:
splits[i]['train'].extend(train_sample)
for test_sample in test:
splits[i]['test'].extend(test_sample)
with open('setting_2.csv','w') as csvfile:
header = ['test','train']
writer = csv.DictWriter(csvfile,fieldnames =header)
writer.writeheader()
# for cross_val in splits:
writer.writerows(splits) ,list中的每个元素都是字典
import csv
with open('names.csv', 'w') as csvfile:
fieldnames = ['first_name', 'last_name']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
...
first_name,last_name
Baked,Beans
Lovely,Spam
Wonderful,Spam
>>> import csv
>>> with open('names.csv') as csvfile:
... reader = csv.DictReader(csvfile)
... for row in reader:
... print(row['first_name'], row['last_name'])
...
Baked Beans
Lovely Spam
Wonderful Spam
读取的时候 , reader是一个对象,不是一个列表,该怎么办?
如果用for循环取出的话,每一个row是一个字典。
字典中原来存储的array 变成了字符串,2-d array 变成了换行符+list+字符串
with open(csv_name,'r') as csv_file:
pred_true= csv.DictReader(csv_file)
for row in pred_true:
y_pred_str = row['y_pred']
y_pred_str = y_pred_str.strip('[]').split(' ')
for i in y_pred_str: # 有些是空字符,有些还有换行符
if i != '':
y_pred_list.append(eval(i))
glob
import glob
glob.glob()
glob给出的不是本机的绝对录路径,而是所给path的最深路径
还没有评论,来说两句吧...