1. 程式人生 > >python常用檔案讀寫

python常用檔案讀寫

1.新建一個txt檔案,有讀寫功能


f = open("mapping2.txt", "w+")
f.write(str(mapping))
f.close()

  2. 用於判斷一個檔案是否存在,不存在則新建一個


if not os.path.exists(new_folder):
        os.mkdir(new_folder)
3.一個資料夾中有多個子資料夾,每個子資料夾中有多個檔案,遍歷每個子資料夾的內容

# encoding:utf-8
import os
import shutil


path1="/home/xionglin/274G2/face0413/dataset"
dst_path="/home/xionglin/274G2/face0413/val"

fs1 = os.listdir(path1)
# fs2 = os.listdir(path2)

for imagefolder in fs1:
    print imagefolder
    new_folder=os.path.join(dst_path,imagefolder)
    print new_folder
    if not os.path.exists(new_folder):
        os.mkdir(new_folder)

    path2 = os.path.join(path1, imagefolder)
    fs2=os.listdir(path2)
    # # for pic in imagefolder:
    print len(fs2)
    # print type(str(path2))
    total_num=len(fs2)
    threshold=int(total_num*0.5)
    print threshold
    num=0
    for pic in fs2:
        # print type(pic)
        # print os.path.join(new_folder,pic)
        if num<=threshold:
            num+=1
            shutil.move(os.path.join(path2,pic), os.path.join(new_folder, pic))
        else:break

4.讀取txt檔案的每一行


import re
fopen0 = open("supplement/SeNet-0.005-64-50-1.txt", 'r')
# fopen0 = open("resnet-cfg/Config2rN.cfg", 'r')
lines0 = fopen0.readlines() #讀取每一行到lines0
model0=[] 
for line in lines0:
    m0 = re.findall(r'(\w*[0-9]+)\w*', line)   #找出每一行中的數字
    # sheet.write(i, 0, m)
    # i = i + 1
    # print m0
    if len(m0)>=3:
        # tem0=m0[1]
        # print tem0
    # print m0[1]
        model0.append(m0[1])
        # model0.append(m0[2])
print model0
print len(model0