Python文件和目录操作整理

读写text数据

with open(filename, 'rt', encoding='utf-8') as f:
    data = f.read()
with open(filename, 'rt', encoding='utf-8') as f:
    for line in f:
        print(line)
with open(filename, 'wt', encoding='utf-8') as f:
    f.write(text1)
with open(filename, 'wt', encoding='utf-8') as f:
    # 也可以使用print函数,指定file参数即可
    print(text1,file=f)

如果是追加模式,wt换成at即可。

使用sys.getdefaultencoding()可以获取到系统默认的编码方式,一般是utf-8

尽量使用with来操作文件,因为它自动帮你管理了文件的打开和关闭,如果是不用with,自己不要忘记了关闭文件。

newline=''参数消除了由于不同操作系统的换行符的差异。

with open(filename, 'rt', encoding='utf-8',newline='') as f:
    ...

使用print函数的时候,注意使用sepend参数,可以提供很多方便。

比如我们要将

row = ('acme', 50, 91.5)连接起来输出,因为str.join()函数要求所有的参数必须是str类型,所以如果使用str.join(),那么需要多做一些工作。

row = ('acme', 50, 91.5)
print(','.join(str(x) for x in row))

如果合理使用printsep参数,那么实现同样的效果,代码是

print(*row, sep=',')

读写二进制数据

with open(filename, 'rb') as f:
    data = f.read()
with open(filename, 'wb') as f:
    f.write(b'Hello World')
with open(filename, 'rb') as f:
    data = f.read(16)
    text = data.decode('utf-8')
with open(filename, 'wb') as f:
    text = 'Hello World'
    f.write(text.encode('utf-8'))

小技巧

如果要求对一个不存在的文件进行写操作,而存在的文件则不进行操作。(这样可以防止覆盖了已存在文件的内容)

常规写法:

import os
if not os.path.exists(filename):
    with open(filename, 'wt') as f:
        f.write('Hello\n')
else:
    print('File already exists!')

更简单的写法,使用openx模式

with open(filename, 'xt') as f:
    f.write('Hello\n')

读写gzip或者bz2压缩文件

import gzip
with gzip.open(filename, 'rt') as f:
    text = f.read()
import bz2
with bz2.open(filename, 'rt') as f:
    text = f.read()
import gzip
with gzip.open(filename, 'wt', compresslevel=5) as f:
    f.write(text)
import bz2
with bz2.open(filename, 'wt', compresslevel=5) as f:
    f.write(text)

处理路径问题

import os
path='C:\\User\\yan\\paper.txt'
print(os.path.basename(path))
print(os.path.dirname(path))
print(os.path.splitext(path))

Output:

paper.txt
C:\User\yan
('C:\\User\\yan\\paper', '.txt')

判断文件或文件夹是否存在

os.path.exists(filename)
os.path.isfile(filename)
os.path.isdir(dirname)
os.path.islink(linkname)
os.path.realpath(path)
os.path.getsize(filename)
os.path.getmtime(filename) #文件修改时间
import time
time.ctime(os.path.getmtime(filename)) #转换为易读的方式
os.listdir(dirname) # 列出dir所有的文件

过滤查找文件或文件夹

import os
#获取所有的文件
file_names = [name for name in os.listdir(dirname) if os.path.isfile(os.path.join(dirname,name))]
#获取所有的文件夹
dir_names = [name for name in os.lsitdir(dirname) if os.path.isdir(os.path.join(dirname,name))]
#获取所有的python文件
py_names = [name for name in os.listdir(dirname) if name.endswith('.py')]
#获取所有的python文件
import glob
py_names = glob.glob('dirname/*.py')
#获取所有的python文件
from fnmatch import fnmatch
py_names = [name for name in os.listdir(dirname) if fnmatch(name,'*.py')]

新建文件和删除文件

open(filename, 'wt').close() #创建一个空文件
os.remove(filename)

复制和移动文件

import shutil
shutil.copyfile(oldfilename, newfilename) #两个参数必须是文件名,不能是文件夹
shutil.copy(oldfilename, newfilename)
shutil.copy(oldfilename, foldername)  #copy第二个参数既可以指定文件名,也可以指定文件夹名

文件夹操作

获取当前的工作文件夹

os.getcwd()

改变当前工作文件夹

os.chdir(dirname)

新建文件夹

os.mkdir(dirname)  #创建单级目录
os.makedirs(dirname/subdirname) #创建多级目录

删除文件夹

os.rmdir(dirname) #删除单级空目录
os.removedirs(dirname/subdirname) #删除多级空目录
import shutil
shutil.rmtree(dirname) #删除目录,不管是空还是非空,是单级目录还是多级目录

复制文件夹

shutil.copytree(oldfoldername, newfoldername)

移动文件夹/文件

shutil.move(oldpos, newpos)