1. 程式人生 > >python_檔案遍歷、檔案讀取、檔案操作

python_檔案遍歷、檔案讀取、檔案操作

一、檔案遍歷

import os

fileDir="D:" + os.sep + "data2"

for root, dirs, files in os.walk(fileDir):

for dir in dirs:

print(os.path.join(root,dir))

for file in files:

print(os.path.join(root,file))  #檔案路徑

            name,suffix = os.path.splitext(file)  #檔名、字尾名

注:for root, dirs, files in os.walk(fileDir): 

                    print

(root) #當前目錄路徑

print(dirs) #當前路徑下所有子目錄

print(files) #當前路徑下所有非目錄子檔案

二、檔案按行讀取,並讀取每行的每個元素

import os

(注:如果是讀取遍歷的檔案:f = open(os.path.join(root,file),"r")

controlFile=open("D:\\DEM2\\control.txt","r")  #呼叫python的open()函式開啟要讀取的檔案
lstcon=controlFile.readlines() #讀取檔案中的內容並寫入到列表
for point in lstcon: #新增一個for 迴圈語句來迭代遍歷lstFires變數中的所有行
     lstvalue=point.split(",") #呼叫split()函式並使用逗號作為分隔符,將分離後的值儲存到列表中,然後賦值給變數lstValues
     ID=int(lstvalue[0])  #使用索引值來獲取
     x=float(lstvalue[1])
     y=float(lstvalue[2])

     z=float(lstvalue[3])

controlFile.close()

三、檔案刪除

os.remove(path)

四、計算檔案大小

                size=os.path.getsize(os.path.join(root,file))

                size1=(size+1024)/1024.0/1024.0  #size單位為位元,化為M

五、中文輸出

import sys


print"序號","資料項名稱","資料內容"
print"序號,資料項名稱,資料內容"
type = sys.getfilesystemencoding() #python編碼轉換到系統編碼輸出
print type


六、進行行篩選

#篩選地理基準影像上的匹配點數,每張像片取100個

p2_fr=open("E:\\test\\sift\\dom\\tfw\\2DSC00261XYZ.txt","r")

p2_fw=open("E:\\test\\sift\\dom\\tfw\\2DSC00261XYZ1.txt","w")

p2_num=len(open("E:\\test\\sift\\dom\\tfw\\2DSC00261XYZ.txt").readlines())

p2_num_hang=p2_num/100

for frp2 inp2_fr.readlines()[0:p2_num:p2_num_hang]:#輸出檔案中間隔一定數量的行#開始,結尾,間隔

    p2_fw.write(str(frp2))

p2_fw.close()

p2_fr.close()

七、對檔案進行切片

import re;

p=re.compile('\n\n',re.S);

fileContent=open('files/辦公室.txt','r',encoding='utf8').read();#讀檔案內容

paraList=p.split(fileContent)#根據換行符對文字進行切片

fileWriter=open('files/0.txt','a',encoding='utf8');#建立一個寫檔案的控制代碼

for paraIndexin range(len(paraList)):#遍歷切片後的文字列表

    fileWriter.write(paraList[paraIndex]);#先將列表中第一個元素寫入檔案中

    if((paraIndex+1)%3==0):#判斷是否寫夠3個切片,如果已經夠了

        fileWriter.close(); #關閉當前控制代碼

       fileWriter=open('files/'+str((paraIndex+1)/3)+'.txt','a',encoding='utf8');#重新建立一個新的控制代碼,等待寫入下一個切片元素。注意這裡檔名的處理技巧。

fileWriter.close();#關閉最後建立的那個寫檔案控制代碼

print('finished');  

八、獲得上一級目錄

1.  parent_path = os.path.dirname(d) #獲得d所在的目錄,d的父級目錄

2.  parent_path  = os.path.dirname(parent_path) ##獲得parent_path所在的目錄即parent_path的父級目錄