国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python文件及目錄操作實例詳解

2020-02-23 01:33:03
字體:
供稿:網(wǎng)友

本文實例講述了Python文件及目錄操作的方法。分享給大家供大家參考。具體分析如下:

在python中對文件及目錄的操作一般涉及多os模塊,os.path模塊。具體函數(shù)以及使用方法在程序中說明。

#!/usr/bin/env python#-*- coding=UTF8 -*-import osimport os.path as opdef change_dir():  ''' 該函數(shù)顯示及改變前目錄 using chdir() to change current dir    getcwd() can show the current working directory  '''  directory="/tmp"  #使用getcwd()返回當(dāng)前目錄  print os.getcwd()  #chdir改變當(dāng)前目錄為:directory目錄  os.chdir(directory)  print os.getcwd()def show_filesOfdir(whichDir):  ''' 此函數(shù)只顯示目錄下的所有文件 using listdir() to shows all of the file execpt directory   join() function catenate 'whichDir' with listdir() returns values   isfile() check that file is a regular file   '''     #listdir() 函數(shù)顯示前目錄的內(nèi)容  for file in os.listdir(whichDir): #利用join()把whichDir目錄及l(fā)istdir() 返回值連接起來組成合法路徑    file_name = op.join(whichDir,file) #isfile()函數(shù)可以判斷該路徑上的文件是否為一個普通文件    if op.isfile(file_name):      print file_namedef printaccess(path):  '''  顯示文件的最后訪問時間,修改時間 shows 'path' the last access time       getatime() return the time of last access of path   stat() return information of a file,use its st_atime return the time of last access   ctime() return a string of local time  '''  import time  #利用ctime()函數(shù)返回最后訪問時間  #getatime()函數(shù)返回最后訪問時間,不過是以秒為單位(從新紀(jì)元起計算)  print time.ctime(op.getatime(path))  #stat()函數(shù)返回一個對象包含文件的信息  stat = os.stat(path)  #st_atime 最后一次訪問的時間  print time.ctime(stat.st_atime)  print the modify time  print "modify time is:",  print time.ctime(op.getctime(path))  print "modify time is:",  #st_ctime 最后一次修改的時間  print time.ctime(stat.st_ctime)def isDIR(path):  ''' 一個os.path.isdir()函數(shù)的實現(xiàn) Implement isdir() function by myself  '''  import stat  MODE = os.stat(path).st_mode  #返回真假值  return stat.S_ISDIR(MODE)if __name__== "__main__":  change_dir()  show_filesOfdir('''/root''')  printaccess('/etc/passwd')  print isDIR('/etc')

希望本文所述對大家的Python程序設(shè)計有所幫助。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 个旧市| 东台市| 焦作市| 广州市| 巫山县| 万载县| 沙坪坝区| 枝江市| 南丹县| 宁海县| 淳安县| 罗平县| 麦盖提县| 唐海县| 莒南县| 海门市| 定兴县| 车致| 阿合奇县| 聂荣县| 龙南县| 福清市| 宁晋县| 灌阳县| 穆棱市| 肇州县| 涟源市| 惠州市| 外汇| 咸丰县| 施甸县| 墨竹工卡县| 宜阳县| 乌苏市| 商水县| 宁津县| 汝城县| 锦屏县| 雷州市| 习水县| 龙里县|