标签:int size rmdir 相对 exce div 返回 close pre
一、文件操作
open(file, mode = ‘r‘, buffering = -1 , encoding=None, errors = None, newline = None, closefd = True,opener = None)
八个参数意义:
一般只使用前两个参数。
文件内容读取:
filename = ‘E:/a.txt‘ try: f = open(filename) except OSError: print(‘打开文件失败‘) else: try: content = f.read() print(content) except OSError: print(‘文件读取失败‘) finally: f.close()
简单代码:
with open(‘E:/a.txt‘, ‘r‘) as f: content = f.read() print(content)
读取文件并复制(w——写入(不存在则创建,存在则覆盖)):
filename = ‘E:/a.txt‘ with open(filename, ‘r‘, encoding=‘utf-8‘) as f: lines = f.readlines() print(lines) copy_f_name = ‘E:/copy_a.txt‘ with open(copy_f_name, ‘w‘, encoding=‘utf-8‘) as copy_f: copy_f.writelines(lines) print(‘{}成功复制到{}‘.format(filename, copy_f_name)) 结果: [‘hellohellohellohello‘] E:/a.txt成功复制到E:/copy_a.txt
二进制文件读写:
二进制文件复制(wb——二进制文件写入(不存在则创建,存在则覆盖)):
filename = ‘E:/头像.jpg‘ with open(filename,‘rb‘) as f: b = f.read() copy_f_name = ‘E:/头像_Copy.jpg‘ with open(copy_f_name,‘wb‘) as copy_f: copy_f.write(b) print(‘二进制文件复制成功!‘)
二、OS模块——系统目录与文件的管理:
import os f_name = ‘E:/a.txt‘ copy_f_name = ‘E:/a_copy.txt‘ with open(f_name, ‘r‘) as f: b = f.read() with open(copy_f_name, ‘w‘) as copy_f: copy_f.write(b) # 判断是否存在,否则文件重命名 try: os.rename(copy_f_name, ‘E:/b.txt‘) except OSError: os.remove(‘E:/b.txt‘) # 输出当前目录及父目录 print(os.listdir(os.curdir)) print(os.listdir(os.pardir)) # 判断路径是否存在,否则删除路径 try: os.mkdir(‘E:/filesdir‘) except OSError: os.rmdir(‘E:/filesdir‘) for i in os.walk(‘E:/桌面‘): print(i)
结果:
三、os.path模块
示例:
import os.path from datetime import datetime f_name = ‘抢火车票.py‘ all_name = r‘C:\Users\Jery\PycharmProjects\CollectImages\抢火车票.py‘ # 基础名部分 basename = os.path.basename(all_name) print(basename) # 目录部分 dirname = os.path.dirname(all_name) print(all_name) # 绝对路径 print(os.path.abspath(f_name)) # 文件大小 print(os.path.getsize(f_name)) # 最近访问时间 atime = datetime.fromtimestamp(os.path.getatime(f_name)) print(atime) # 最近修改时间 mtime = datetime.fromtimestamp(os.path.getmtime(f_name)) print(mtime) # 创建时间 ctime = datetime.fromtimestamp(os.path.getctime(f_name)) print(ctime) print(os.path.isdir(dirname)) print(os.path.isfile(f_name)) print(os.path.exists(f_name)) 结果: 抢火车票.py C:\Users\Jery\PycharmProjects\CollectImages\抢火车票.py C:\Users\Jery\PycharmProjects\CollectImages\抢火车票.py 5673 2019-03-27 11:19:39.251669 2019-03-27 11:19:39.251669 2019-03-15 19:48:48.315313 True True True Process finished with exit code 0
标签:int size rmdir 相对 exce div 返回 close pre
原文地址:https://www.cnblogs.com/Jery-9527/p/10607219.html