Python文件及目录操作实例详解
本文实例讲述了Python文件及目录操作的方法。分享给大家供大家参考。具体分析如下:
在python中对文件及目录的操作一般涉及多os模块,os.path模块。具体函数以及使用方法在程序中说明。
#!/usr/bin/env python #-*- coding=UTF8 -*- import os import os.path as op def change_dir(): ''' 该函数显示及改变前目录 using chdir() to change current dir getcwd() can show the current working directory ''' directory="/tmp" #使用getcwd()返回当前目录 print os.getcwd() #chdir改变当前目录为:directory目录 os.chdir(directory) print os.getcwd() def show_filesOfdir(whichDir): ''' 此函数只显示目录下的所有文件 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() 函数显示前目录的内容 for file in os.listdir(whichDir): #利用join()把whichDir目录及listdir() 返回值连接起来组成合法路径 file_name = op.join(whichDir,file) #isfile()函数可以判断该路径上的文件是否为一个普通文件 if op.isfile(file_name): print file_name def 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()函数返回最后访问时间 #getatime()函数返回最后访问时间,不过是以秒为单位(从新纪元起计算) print time.ctime(op.getatime(path)) #stat()函数返回一个对象包含文件的信息 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()函数的实现 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程序设计有所帮助。

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Linux 터미널에서 Python 버전을 보려고 할 때 Linux 터미널에서 Python 버전을 볼 때 권한 문제에 대한 솔루션 ... Python을 입력하십시오 ...

Python의 Pandas 라이브러리를 사용할 때는 구조가 다른 두 데이터 프레임 사이에서 전체 열을 복사하는 방법이 일반적인 문제입니다. 두 개의 dats가 있다고 가정 해

Python : 모래 시계 그래픽 도면 및 입력 검증을 시작 하기이 기사는 모래 시계 그래픽 드로잉 프로그램에서 Python 초보자가 발생하는 변수 정의 문제를 해결합니다. 암호...

Python 스크립트는 특정 위치에서 Cursor 위치로 출력을 어떻게 제거합니까? Python 스크립트를 작성할 때 이전 출력을 커서 위치로 지우는 것이 일반적입니다 ...

Python 크로스 플랫폼 데스크톱 응용 프로그램 개발 라이브러리 선택 많은 Python 개발자가 Windows 및 Linux 시스템 모두에서 실행할 수있는 데스크탑 응용 프로그램을 개발하고자합니다 ...

파이썬 프로그래밍에서 Python 매개 변수 주석의 대체 사용법, 매개 변수 주석은 개발자가 기능을 더 잘 이해하고 사용하는 데 도움이되는 매우 유용한 기능입니다 ...

파이썬에서 문자열을 통해 객체를 동적으로 생성하고 메소드를 호출하는 방법은 무엇입니까? 특히 구성 또는 실행 해야하는 경우 일반적인 프로그래밍 요구 사항입니다.

많은 개발자들이 PYPI (PythonPackageIndex)에 의존합니다 ...
