首页 Python文件操作小结
文章
取消

Python文件操作小结

打开文件

1
>>> file=open(file_path[, access_mode][, buffering])

读取文件

read()方法从一个打开的文件中读取一个字符串。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。

1
>>> file.read([count])

将字符串写进文件

1
>>> file.write(str)

删除文件

1
2
>>> import os
>>> os.remove('work.xls')

重命名文件或目录

1
2
>>> import os
>>> os.rename('a.txt','b.txt')

复制文件或目录

1
2
>>> import shutil
>>> shutil.copyfile('/home/work.xls','/home/work/work.xls')

移动文件或目录

1
2
>>> import shutil
>>> shutil.move('/home/work.xls','/home/work/work.xls')

获取文件大小

单位字节

1
2
3
>>> import os
>>> os.path.getsize('work.zip')
4227432

创建目录

创建单个目录,可以是绝对路径,也可以是相对路径

1
2
3
>>> import os
>>> os.mkdir('work')
>>> os.mkdir('../work')

创建多层目录

1
2
>>> import os
>>> os.makedirs('work/ibm')

切换目录

1
2
>>> import os
>>> os.chdir('/etc')

删除目录

删除非空目录

1
2
>>> import os
>>> os.rmdir('home')

从子目录开始删除,然后删除上级目录,若目录非空则不再删除

1
2
>>> import os
>>> os.removedirs('/home')

全部删除,不管是否为空

1
2
>>> import shutil
>>> shutil.rmtree('/home/work')

复制文件夹

新旧dir只能是目录,且新目录不存在

1
2
>>> import shutil
>>> shutil.copytree('old_dir','new_dir')

获取当前工作目录

也即python脚本的目录

1
2
3
>>> import os
>>> os.getcwd()
'/Users/uphie/Music'

获取当前工作目录下的文件和目录

返回一个数组,包含所有的文件名和目录名

1
2
3
>>> import os
>>> os.listdir()
['.DS_Store', '.localized', 'Audio Music Apps', 'GarageBand', 'iTunes', '网易云音乐']

检查指定路径是否是文件

返回 True/False

1
2
3
>>> import os
>>> os.path.isfile('apple.txt')
True

检查指定路径是否是目录

返回 True/False

1
2
3
>>> import os
>>> os.path.isdir('/home')
True

检查指定路径是否存在

返回 True/False

1
2
3
>>> import os
>>> os.path.exist('/home/work.xls')
True

获取文件目录名

1
2
3
>>> import os
>>> os.path.dirname('/home/work.xls')
'/home'

获取文件名

1
2
3
>>> import os
> os.path.basename('/home/work.xls')
'work.xls'

获取文件绝对路径

1
2
>>> import os
>>> os.path.abspath(file_path)

获取当前系统平台

Windows:nt
Linux/Mac:posix

1
2
3
>>> import os
>>> os.name
'posix'

使用shell命令

1
2
>>> import os
>>> os.system('rm abc.txt')

使用shell命令并获得输出

python2

1
2
3
4
5
6
>>> import commands
>>> (status, output) = commands.getstatusoutput('cat my.txt')
>>> status
0
>>> content
'This is a text file!'

python3

1
2
3
4
5
6
>>> import subprocess
>>> (status,content) = subprocess.getstatusoutput('cat my.txt')
>>> status
0
>>> content
'This is a text file!'
本文由作者按照 CC BY 4.0 进行授权