python基於檔案操作__python

來源:互聯網
上載者:User

路漫漫其修遠兮

Python中對檔案檔案夾的操作

在windows可能出現問題。當使用os模組中的mknod方法時,Traceback報以下錯誤:

AttributeError: 'module' object has no attribute 'mknod'

原因是因為windows檔案系統與linux檔案系統不同,沒有node的概念,所以提示錯誤。

當在使用追加開啟檔案的時候,python會自動建立檔案。

檔案操作

目標操作

例子

python代碼:

# -*- coding:utf-8 -*-

import re

import os

import time

#str.split(string)分割字串

#'串連符'.join(list) 將列表組成字串

def change_name(path):

global i

if not os.path.isdir(path) and not os.path.isfile(path):

return False

if os.path.isfile(path):

file_path = os.path.split(path) #分割出目錄與檔案

lists = file_path[1].split('.') #分割出檔案與副檔名

file_ext = lists[-1] #取出尾碼名(列表切片操作)

img_ext = ['bmp','jpeg','gif','psd','png','jpg']

if file_ext in img_ext:

os.rename(path,file_path[0]+'/'+lists[0]+'_fc.'+file_ext)

i+=1 #注意這裡的i是一個陷阱

#或者

#img_ext = 'bmp|jpeg|gif|psd|png|jpg'

#if file_ext in img_ext:

# print('ok---'+file_ext)

elif os.path.isdir(path):

for x in os.listdir(path):

change_name(os.path.join(path,x)) #os.path.join()在路徑處理上很有用

img_dir = 'D:\\xx\\xx\\images'

img_dir = img_dir.replace('\\','/')

start = time.time()

i = 0

change_name(img_dir)

c = time.time() - start

print('程式運行耗時:%0.2f'%(c))

print('總共處理了 %s 張圖片'%(i))




想擷取更多視頻或者有任何學習問題
歡迎加入Python交流群
626062078

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.