基本文件操作
创建和打开文件
open()函数语法格式:
file = open(filename[,mode[,buffering]])
关闭文件
close()函数的语法格式:
file.close()
mode函数的参数值
读取文件
1.read()函数的语法格式
file.read([size])
f = open("C:\\Users\\de'l'l\\Desktop\\myfile.txt","r") #打开文件
d = f.read() #读取文件
print(d)
f.close()
2.读取一行
readline()方法的基本语法格式:
file.readline()
f = open("C:\\Users\\de'l'l\\Desktop\\myfile.txt","r") #打开文件
d = f.readline() #读取一行
d = f.readline()
print(d,d1)
f.close()
3.读取全部行
readlines()方法的基本语法格式:
file.readlines()
读取指定字符
seek()方法:将文件的指针移动到新的位置。
seek()方法的基本语法格式:
file.seek(offset[,whence])
参数说明:
file:表示已经打开的文件对象。
offset:用于指定移动的字符个数,其具体位置与whence参数有关。
whence:用于指定从什么位置开始计算。值为0表示从头开始计算,值 为1表示从当前位置开始计算,值为2表示从文件尾开始计算,默认为0。
with open("C:\\Users\\de'l'l\\Desktop\\myfile.txt","r") as f:
f.seek(12)
d = f.read(10)#从第12个字符开始读取10个字符
print(d)
with语句实现
with expression as target:
with-body
参数说明:
expression:用于指定一个表达式,这里可以是打开文件的open()函数。
target:用于指定一个变量,并且将expression的结果保存到该变量中。
with-body: 用于指定with的语句体,其中可以是执行with语句后相关的一些操作语句。
with open("C:\\Users\\de'l'l\\Desktop\\myfile.txt","r") as f:
d = f.read()
print(d)
写入文件内容
write()方法的语法格式:
file.write(string)
with open("C:\\Users\\de'l'l\\Desktop\\myfile1.txt","w") as f:
f.write("白日依山尽")
f.close()
用flush()的方法将缓存的内容写入文件
with open("C:\\Users\\de'l'l\\Desktop\\myfile1.txt","w") as f:
f.write("黄河入海流")
f.flush()
追加内容到文件中
with open("C:\\Users\\de'l'l\\Desktop\\myfile1.txt","a") as f:
f.write(",黄河入海流\n欲穷千里目,更上一层楼。")
f.close()
目录操作
os模块提供的与目录相关的函数
os.path模块提供的与目录相关的函数
1.获取当前工作目录(相对路径:结合当前路径确定文件位置)
os.getcwd()
import os
print(os.getcwd())
通过相对路径打开文件
import os
print(os.getcwd())
with open("message.txt") as file
2.获取一个文件的绝对路径(绝对路径直接确定文件位置)
os.path.abspath(path)
import os
print(os.path.abspath(r"demo\test.txt"))
3.拼接路径
os.path.join(path1[,path2[,……]])
import os
print(os.path.join(r"python",r"demo\test.txt"))
4.判断目录是否存在(还可以判断文件是否存在)
os.path.exists(path)
import os
print(os.path.exists(r"D:\python"))
5.创建一级目录
os.mkdir(path,mode=0o777)
import os
if not os.path.exists("D:\\demo"): #(判断该目录是否存在)
os.mkdir("D:\\demo") #创建一级目录
else:
print("该目录已经存在。")
6.创建多级目录
os.makedirs(path,mode=0o777)
os.makedirs("D:\\demo\\test\\demo\\yyb")
7.删除空目录
os.rmdir(path)
import os
if os.path.exists(r"D:\\demo\\test\\demo\\yyb"):
os.rmdir(r"D:\\demo\\test\\demo\\yyb") #删除空目录yyb
print("目录删除成功")
else:
print("目录不存在")
8.删除非空目录
import shutil
shutil.retree(path)
import os,shutil
if os.path.exists(r"D:\\demo\\test\\demo"):
shutil.rmtree(r"D:\\demo\\test\\demo") #删除test目录下不为空的demo子目录(demo子目录中还有文件)
print("目录删除成功")
else:
print("目录不存在")