前言
日常開發(fā)過程中,我們常常需要用到文件以及文件夾操作,這些操作在linux命令行下本身就有,但是一旦我們需要將文件進行自動化操作,如寫入、遍歷讀取、或者上傳文件等等操作,我們就需要在Python下進行文件自動化操作的編程。本文主要介紹這些文件、文件夾操作,并作了一定歸納。
?
一、Python文件I/O操作
1、 打開文件:file object = open(file_name [, access_mode][, buffering])
注:
access_mode決定了打開文件的模式:只讀,寫入,追加等
。默認文件訪問模式為只讀(r),其他常用模式如下:
2、 file對象屬性:
(1) file.closed——如果已經(jīng)關(guān)閉則返回True,否則返回False;
(2) file.mode——返回打開的模式;
(3) file.name——返回文件名稱;
3、 關(guān)閉文件:file.closed();
4、 寫入內(nèi)容:file.write(string);
5、 讀取文件內(nèi)容: file.read(
6、 重命名文件: os.rename(<當前文件名>, <新文件名>)
7、 刪除文件: os.remove(<文件名>)
8、 判斷文件是否存在: os.path.exists(self.local_file_path)——存在返回True,否則返回False;
9、 獲取文件大小: fsize = os.path.getsize(<文件名>)——單位為B;
?
二、Python文件夾操作
1、創(chuàng)建文件夾:os.mkdir(<新文件夾>);
2、進入(cd)某個文件夾路徑: os.chdir(<文件夾>);
3、獲取當前所在路徑: os.getcwd();
4、刪除文件夾: os.rmdir(<文件夾>);
?
三、Python文件上傳操作
常用的分為FTP上傳和html表單上傳文件兩種
,F(xiàn)TP上傳的常用方法如下:
1、FTP.connect(
2、FTP.login(
3、FTP.cwd(
4、FTP.nlst():獲得目錄下文件;
5、FTP.retrbinary(
6、FTP.delete(
7、ftp.storbinary(
8、ftp.quit():退出FTP服務(wù)器;
?
四、python接收文件操作
對于要接收的html傳過來的文件,python一般是基于框架對文件進行接收,當然也可以通過底層實現(xiàn)。
常用的框架接收文件的案例有:Flask、Django、bottle等
,其中bottle是最輕量級的。
1、Flask實現(xiàn)案例:
# 文件上傳
import flask, os, sys,time
from flask import request
interface_path = os.path.dirname(__file__)
sys.path.insert(0, interface_path) #將當前文件的父目錄加入臨時系統(tǒng)變量
server = flask.Flask(__name__, static_folder='static')
@server.route('/', methods=['get'])
def index():
return '
'
@server.route('/upload', methods=['post'])
def upload():
fname = request.files['img'] #獲取上傳的文件
if fname:
t = time.strftime('%Y%m%d%H%M%S')
new_fname = r'static/' + t + fname.filename
fname.save(new_fname) #保存文件到指定路徑
return '
' % new_fname
else:
return '{"msg": "請上傳文件!"}'
print('----------路由和視圖函數(shù)的對應(yīng)關(guān)系----------')
print(server.url_map) #打印路由和視圖函數(shù)的對應(yīng)關(guān)系
server.run(port=8000)
2、bottle實現(xiàn)案例:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from bottle import *
base_path = os.path.dirname(os.path.realpath(__file__)) # 獲取腳本路徑
upload_path = os.path.join(base_path, 'upload') # 上傳文件目錄
if not os.path.exists(upload_path):
os.makedirs(upload_path)
@route('/', method='GET')
@route('/upload', method='GET')
@route('/index.html', method='GET')
@route('/upload.html', method='GET')
def index():
"""顯示上傳頁"""
return HTML
@route('/upload', method='POST')
def do_upload():
"""處理上傳文件"""
filedata = request.files.get('fileField')
if filedata.file:
file_name = os.path.join(upload_path, filedata.filename)
try:
filedata.save(file_name) # 上傳文件寫入
except IOError:
return '上傳文件失敗'
return '上傳文件成功, 文件名: {}'.format(file_name)
else:
return '上傳文件失敗'
@route('/favicon.ico', method='GET')
def server_static():
"""處理網(wǎng)站圖標文件, 找個圖標文件放在腳本目錄里"""
return static_file('favicon.ico', root=base_path)
@error(404)
def error404(error):
"""處理錯誤信息"""
return '404 發(fā)生頁面錯誤, 未找到內(nèi)容'
run(port=8080, reloader=False) # reloader設(shè)置為True可以在更新代碼時自動重載
參考鏈接:https://bbs.csdn.net/topics/392190705
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
