Python 檔案命令總結

2021-09-19 04:27:53 字數 1802 閱讀 9919

讀取 excel:

import xlrd

data = xlrd.open_workbook('gt.xlsx')

table = data.sheet_by_name('sheet1')

for i in range(table.nrows):

imgname, gt = table.row_values(i)[0], table.row_values(i)[1]

新建、刪除:

import os

# 建立檔案

with open('a.txt', 'w') as f:

f.write('hello world')

# 讀取檔案

with open('a.txt', 'r') as f:

text = f.read() # f.readlines()

# 刪除檔案

os.remove(path)

# 建立資料夾

# 區別:若 dir_path 的父資料夾不存在,則 mkdir 建立失敗,而 mkdirs 會連同父資料夾一同建立;

os.mkdir(dir_path)

os.mkdirs(dir_path)

# 刪除資料夾

os.rmdir(dir_path)

移動、複製:

import os, glob, shutil

src_dir = './datasets'

dst_dir = './new_dataset'

filelist = glob.glob('./datasets/*/*.jpg') # 當前目錄的二級目錄下所有jpg影象檔案的路徑

for file in filelist:

filename = os.split(file)[-1]

shutil.copyfile(file, os.path.join(dst_dir, filename)) # 複製檔案

# shutil.move(file, os.path.join(dst_dir, filename)) # 移動檔案

路徑、搜尋:

import os, glob

# 獲取檔案字尾名(.jpg, .png, .txt ...)

suffix = os.path.splitext(filepath)[-1]

# 獲取檔名(不含路徑)或路徑

filename = os.path.split(filepath)[-1]

dir = os.path.split(filepath)[0]

# 連線路徑、連線路徑與檔名

filepath = os.path.join(dir, filename)

# 判斷路徑是否存在

if not os.path.exists(filepath):

os.mkdir(filepath) # 不存在則建立

# 切換路徑

os.chdir(new_dir)

# 顯示資料夾下所有檔案(或符合條件的檔案)

# 顯示檔案所在的資料夾路徑

os.path.dirname(filepath)

python檔案操作總結 python檔案操作總結

python 中os.path模組用於操作檔案或資料夾 os.path.exists path 判斷檔案路徑是否存在 dir c windows if os.path.exists dir print dir exists else print no exists os.path.isfile pa...

Linux 檔案命令總結

基礎命令 常用 linux 命令 伺服器登入 ssh lx 10.1.2.3 伺服器配置生效 source bashrc 刪除使用者 ssh root 10.141.1.10 root 登入伺服器 userdel name 刪除name使用者 新增使用者 useradd d search odin ...

Python 檔案處理 總結

檔案處理 包括三個步驟 1,開啟檔案。2,操作檔案。3,關閉檔案。下面將逐一介紹 1,開啟檔案 f open file,mode r encoding utf 8 推薦使用with開啟 python中用open 關鍵字開啟檔案,必須引數 檔名稱file 包含檔案的路徑 e python webdri...