python文件操作(IO)
**python模块导入方法
import queue as q
from queue import *
from queue import insert,pop
q.insert(1)
q.insert(2)
print(q.pop())
print(q.pop())
-
文件读写
-
如何创建目录、文件
-
目录删除、文件删除
-
列举目录所有文件
-
os.path模块判断文件或是目录是否存在
#如何打开文件 try: f=open(file='C:/1234.txt')#打开文件并返回文件句柄且文件要写后缀 print(f.readlines()) except IOError as e: pass finally: f.close()#资源释放 #输出:['1\n', '2\n', '34\n', '5\n']
#如何打开文件 try: f=open(file='C:/1234.txt')#打开文件并返回文件句柄 print(f.readline()) print(f.readline()) print(f.readline()) print(f.readline()) except IOError as e: pass finally: f.close()#资源释放 #输出:#1 #2 #34 #5
#如何打开文件 try: f=open(file='C:/1234.txt')#打开文件并返回文件句柄 print(f.readline(3))#指定每行读入的最大字节数 print(f.readlines(5))#括号内为限制总字节数(*灵活) except IOError as e: pass finally: f.close()#资源释放 #输出:1 #['2\n', '34\n', '5\n']
import os.path as p try: file_path=input('请输入文件全路径:') if os.path.exists(file_path): f=open(file=file_path) print(f.readlines()) except IOError as e: raise e finally: f.close()#资源释放 #输出: #请输入文件全路径:C:\1234.txt #['1\n', '2\n', '34\n', '5\n']
import os.path as op file_path='C:/1234.txt' if op.exists(file_path): with open(file=file_path) as f: print(f.readlines()) #输出:['1\n', '2\n', '34\n', '5\n']
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-04GW3tna-1605593774430)(C:\Users\User\AppData\Roaming\Typora\typora-user-images\image-20201106194712068.png)]
-
如何查看当前文件句柄的偏移量
with open(file='C:/1234.txt',mode='w+')as f: f.write('I love J.') f.seek(0)#强制让文件偏移到某个位置上 print(f.tell())#偏移量位置 print(f.readlines()) #输出:0 #['love J.']
-
保留同时写入
with open(file='C:/1234.txt',mode='ab+')as f: f.write("i love J".encode()) f.seek(0)#强制让文件偏移到某个位置上 print(f.tell())#偏移量位置 print(f.readlines())
`