1. 程式人生 > 其它 >python學習筆記第6章:系統與檔案操作

python學習筆記第6章:系統與檔案操作

檔案讀取

readline() 讀取一行

readlines() 讀取全部,讀到列表

read() 讀取全部,讀到字串

6.1手動開啟關閉檔案

src = r‘/usr/local/abc.txt’ #定義路徑字串

f= open(src,’r’) 以只讀模式開啟檔案abc.txt,f是檔案資訊

f.write(‘ha ha ha’) 將ha ha ha寫入f

Print(f.read() )

f.close() 關閉檔案

6.2自動開啟關閉檔案

with open(‘path’,r+) as f: 以讀+寫方式讀取檔案到f

yw_list = f.readline().strip()讀取檔案第一行,並去掉換行等

yw_list = yw_list.split(',')將字串檔案轉為列表

for i in ['分公司', '網格', 'user_name', 'login_name']: # 刪除指定列

yw_list.remove(i)

for i in f:

i = i.split() 遍歷每一行,並將字串轉換為列表,預設空格分隔

6.3遍歷目錄

#遍歷多層目錄

src = r’xxx’

for dirpath,dirnames,filenames in os.walk(src):

for filename in filenames:

os.path.join(dirpath, filename)#拼接得到完整路徑

#遍歷單層

from os import listdir

#自動在指定資料夾獲取檔案

work_path = 'E:\data\qq' #填寫路徑

for s in listdir(work_path): #listdir()獲取路徑內全部檔案到列表中

if '銷售經理層級' in s:

manager_path = work_path + '\\' + s

elif '營業廳層級' in s:

channel_path = work_path + '\\' + s

elif '網格層級' in s:

zone_path = work_path + '\\' + s

6.4檔案格式轉換

方法一:pandas

import pandas

tmp = read_csv(manager_path) #讀取csv檔案

tmp.to_csv(路徑,encoding='utf-8',index=None) 轉換格式為utf-8

tmp.columns #獲取表頭

方法二:codecs

import codecs

src='E:/2020-09-15.csv' #路徑要用斜槓, 或者加r轉化

dst='E:/hhhhh.csv'

with codecs.open(src, "r", "GB18030") as sourceFile:

with codecs.open(dst, "w", "utf-8") as targetFile:

while True:

contents = sourceFile.read()

if not contents:

break

targetFile.write(contents)

6.5系統與目錄操作

執行系統命令

import subprocess

#run和Popen可互換,舊版本可能沒有run

subprocess.Popen("ls") #win系統或linux系統無引數時

subprocess.Popen("ls -l", shell=True)

#linux系統有引數時,不用print,會直接輸出

其他選項

stdout=subprocess.PIPE#獲取標準輸出

stderr=subprocess.STDOUT #獲取錯誤輸出

stdin=subprocess.PIPE #標準輸入

sout ,serr = res.communicate() #將標準輸出賦值給引數

executable=#可指定要用的shell,預設/bin/sh

encoding='utf-8' #指定編碼

目錄與檔案操作

import os

os.rename(old_path,new_path) 重新命名檔案或目錄

os.remove(‘path’) 刪除檔案,不能刪除目錄

os.unlink(‘path’) 同上,不能刪除正在使用的檔案

os.rmdir(path)刪除空目錄

os.removedirs(path) 刪除目錄及子目錄

os.mkdir(path[, mode])新建目錄

os.getcwd()獲取當前所在目錄

os.stat(path) 獲取指定路徑的資訊

os.renames(old, new) 遞迴地重新命名目錄或檔案

os.path.join(‘路徑’,’檔名’)將路徑和檔名拼接起來或許能用列表

os.path.abspath(‘檔名’) 獲取檔案的絕對路徑

os.path.exists(‘檔名’) 檢查檔案或路徑是否存在,bool型

os.path.isdir(src)指定路徑是否是資料夾

os.listdir(‘src’) 遍歷目錄,只能遍歷一層

6.6圖片識別

安裝tesseract-ocr和中文包tessdata

pillow

pyocr

pytesseract #和pyocr二選一

from PIL import Image

from pyocr import tesseract

im = Image.open(src)

im = im.convert(‘L’) #L轉為黑白模式,其它選項點陣圖,RGB等

im.save(‘temp.png’) #儲存圖片

code = tesseract.image_to_string(im) #識別圖片中的字元

print(code ) #打印出識別的內容

#還可進行二值化處理