文件读取方式1:
try:
f = open(r"1.txt")
print(f.read())
finally:
if f:
f.close()
文件读取方式2,常用方式:
with open(r"1.txt") as ff:
print(ff.read())
文件写入:with open(r"1.txt",'w') as ff:
ff.write("aaa")
在python中对文件和目录的操作经常用到os模块和shutil模块,常用方法如下:
os.getcwd() : 获取当前python文件路径
os.listdir() : 获取制定目录中的文件和目录
os.remove()
os.removedirs() : 删除多个空目录
os.path.isfile()
os.path.isdir()
os.path.isabs()
os.path.exists()
os.path.split() : 分离目录目录和文件名称
os.path.splitext() : 分离文件扩展名称
os.path.dirname()
os.path.basename()
os.getenv() : 获取环境变量
os.putenv() : 设置环境变量
os.linesep() 给出当前平台使用的行分隔符 windows使用 '\r\n' linux 使用 '\n' mac使用'\r'
os.name 指示正在使用的平台,windows 为 ‘nt’ linux 为 'posix'
os.rename(old,new) 重命名文件或目录
os.makedirs() 创建多级目录
os.mkdir() 创建当个目录
os.stat() 获取文件属性
os.chmod() 修改文件权限与时间戳
os.getsize()
shutil.copytree("olddir","newdir")
shutil.copyfile("oldfile","newfile")
shutil.move("","")
shutil.rmtree("dir") 空目录和有内容的目录都可以删除
os.rmdir("") 只能删除空目录