博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python文件(夹)基本操作
阅读量:7022 次
发布时间:2019-06-28

本文共 1837 字,大约阅读时间需要 6 分钟。

1、判断文件(夹)是否存在。

1
os.path.exists(pathname)

2、判断路径名是否为文件。

1
os.path.isfile(pathname)

3、判断路径名是否为目录。

1
os.path.isdir(pathname)

4、创建文件。

1
2
os.mknod(filename)    
#windows下不可用
open
(filename, 
"w"
)   
#记得要关闭

5、复制文件。

1
2
shutil.copyfile(
"oldfile"
"newfile"
)   
#oldfile和newfile都只能是文件,目标文件会被覆盖
shutil.copy(
"oldfile"
"newfile"
)   
#oldfile只能是文件,newfile可以是文件,也可以是目标目录

6、删除文件。

1
os.remove(filename)

7、清空文件。

1
2
3
4
file 
= 
open
(
"test.txt"
, w)
file
.seek(
0
)     
file
.truncate() 
#注意文件指针的位置
file
.close()

8、创建目录。

1
2
os.mkdir(pathname)        
#创建单级目录
os.makedirs(pathname)     
#递归创建多级目录

9、复制目录。

1
shutil.copytree(
"olddir"
"newdir"
#olddir和newdir都只能是目录,且newdir必须不存在

10、重命名文件或目录。

1
os.rename(oldname, newname)

11、移动文件或目录。

1
shutil.move(oldpath, newpath)

12、删除目录。

1
2
3
4
5
6
os.rmdir(
"dir"
)     
#不能删除非空目录
'''
#可以删除非空目录,目录打开时也能删除
#约等于'rd /Q /S dir'
'''
shutil.rmtree(
"dir"
)

13、切换目录。

1
os.chdir(newpath)

14、open常用模式。

1
2
3
4
'r'
:  只读(缺省。如果文件不存在,则抛出错误。)
'w'
:  只写(如果文件不存在,则自动创建文件。)
'a'
:  追加
'r+'
: 读写

15、由全路径名的到路径和文件名。

1
2
3
4
5
>>> pathfile 
= 
r
'D:\abc\def\ghi.txt'
>>> os.path.dirname(pathfile)
'D:\\abc\\def'
>>> os.path.basename(pathfile)
'ghi.txt'

16、获取文件大小。

1
2
3
os.path.getsize(pathfile)    
#单位为字节(Byte)
#or
os.stat(pathfile).st_size

17、获取文件创建/修改/访问时间。

1
2
3
os.path.getctime(pathfile)    
#创建时间
os.path.getmtime(pathfile)    
#修改时间
os.path.getatime(pathfile)    
#访问时间

18、获取当前文件目录绝对路径。

1
2
3
4
5
6
7
import 
os, sys
 
if 
__name__ 
=
= 
"__main__"
:
    
os.chdir(
'E:\\'
)
    
print
(sys.path[
0
])
    
print
(os.path.abspath(
'.'
))
    
print
(os.path.dirname(os.path.abspath(__file__)))

19、文件同步。

1
2
3
fileObj.write(text)
fileObj.flush()
os.fsync(fileObj.fileno())

20、获取文件扩展名

1
2
3
4
>>> os.path.splitext(r
'D:\tmp\3.jpg'
)[
1
]
'.jpg'
>>> os.path.splitext(
'3.jpg'
)[
1
]
'.jpg'

相关阅读:

1、

2、

3、

***  ***

本文转自walker snapshot博客51CTO博客,原文链接http://blog.51cto.com/walkerqt/1264285如需转载请自行联系原作者

RQSLT

你可能感兴趣的文章
pipework let's assign static IP to docker container simple.
查看>>
gentoo prefix重生(llvm/clang)
查看>>
线程池的一点理解
查看>>
MacOS下shh,sftp,scp简单使用
查看>>
Android(支持kotlin) 新版Bintray-极简上传Library到JCenter,可上传自定义maven仓库
查看>>
css3毛玻璃
查看>>
vue生命周期
查看>>
Vue响应式原理源码浅析
查看>>
RxSwift (二) Working with Subjects
查看>>
2018年终总结与展望 | 掘金年度征文
查看>>
HTML常用标签
查看>>
UITesting常见问题收集
查看>>
AQS同步组件--Semaphore
查看>>
webpack系列之五module生成1
查看>>
关于Spring Cloud—环境变化
查看>>
吴颖二:12.13 晚评 美联储加息决议会否引起多头者“猛攻”
查看>>
Foundation中的类簇和Swizzle
查看>>
最新iOS面试真题大全
查看>>
Hibernate初级入门
查看>>
3. 怎么解决拖延问题?
查看>>