"""
1、文件的读取
(1)读取文件:open
1、file:指定文件的路径
路径可以分成相对路径和绝对路径
2、mode:指定文件的读取的的模式:
1、'r' open for reading (default) 表示的是读模式
2、'w' open for writing, truncating the file first 表示的是写模式
3、'x' create a new file and open it for writing 表示的创建模式
4、'a' open for writing, appending to the end of the file if it exists 表示的是追加写入
剩余的用的会比较少。
3、readline:一次读取一行数据
4、readlines:读取所行的数据
5、读取文件的方式:
一、使用opan方法读取
二、使用with open的方式
两者的区别是在于open方法是需要手动关闭,然而对于with open来说是不需要手动关闭的。
2、文件的写入:
(1)写入文件:将模式调成"w"写入模式
(2)写入的模式:
1、默认是使用覆盖写入的模式
2、将模式改成"a",表示的是追加写入
"""
1、文件读取:
文件读取的方式分成两种,分别是open和with open,两种的区别在于当文件读取结束之后,open方式需要关闭连接,但是使用with open的方式不需要
1、open方式:
#1、文件读取,类似Java中的io流,使用方法open:
#读取学生信息表:
file = open(file= "D:\code\pythonProject\pythonProject\数据\students.txt",mode="r",encoding="utf-8")
#读取所有行的数据,返回的是一个列表:
stus = file.readlines()
print(stus)
#使用列表推导式的方式:
stu = [stu.split(",") for stu in stus]
print("使用列表推导式后的集合是:{}".format(stu))
#去除列表中的换行符:strip
stu1=[ stu.strip() for stu in stus]
print("去除换行符过后的学生表数据是%s"%(stu1))
#关闭文件
file .close()
2、with open方式:
#使用with open的方式去读取数,连接就不需要手动关闭:
with open(file="D:\code\pythonProject\pythonProject\数据\students.txt",mode="r",encoding="utf-8") as file :
stu2 = [ stu.strip() for stu in file.readlines()]
print(stu2)
2、讲数据存储写入到文件中:也是可以分成两种分别是open方式和with open的方式:
#2、将数据存储到文件中:
with open(file ="/data/stu.txt", mode="w", encoding="utf-8") as file :
#先读取文件:
for stu3 in stu2:
file.write(stu3)
file.write("\n")