python⽂件操作
⽂件操作的作⽤就是把⼀些内容(数据)存储存放起来,可以让程序下⼀次执⾏的时候直接使
⽤,⽽不必重新制作⼀份,省时省⼒。
- ⽂件操作步骤
- 打开⽂件
- 读写等操作
- 关闭⽂件
在python,使⽤open函数,可以打开⼀个已经存在的⽂件,或者创建⼀个新⽂件,语法如下:
name:是要打开的⽬标⽂件名的字符串(可以包含⽂件所在的具体路径)。
mode:设置打开⽂件的模式(访问模式):只读、写⼊、追加等。
- w 和 a 模式:如果⽂件不存在则创建该⽂件;如果⽂件存在, w 模式先清空再写⼊, a 模式
直接末尾追加。 - r 模式:如果⽂件不存在则报错。
str1 = 'I like Python'
str2 = '我爱学习, 学习使我快乐'
# f = open('hello.txt', mode='w')
# 绝对路径: 从头到尾
# /Users/ericli/PycharmProjects/mmx
# C:\Users\ericli\PycharmProjects\mmx
# f = open('hello.txt', mode='w', encoding='UTF-8')
f = open('hello.txt', mode='w', encoding='UTF-8')
# 没有hello.txt吗, 会为我们自定创建一个
# f.write(str1)
f.write(str2)
f.close()
读去文件
# open('hello.txt') # FileNotFoundError: [Errno 2] No such file or directory: 'hello.txt'
# f = open('/Users/ericli/PycharmProjects/mmx/day10/data/hello.txt',mode='r')
# .. 上一个目录, .当前目录
f = open('data/hello.txt', mode='r')
# data = f.read()
# f.read(num)num表示要从⽂件中读取的数据的⻓度(单位是字节),如果没有传⼊num,那么就表示读取⽂件中所有的数据。
# readlines可以按照⾏的⽅式把整个⽂件中的内容进⾏⼀次性读取,并且返回的是⼀个列表,其中每⼀⾏的数据为⼀个元素。
# data = f.readlines()
data = f.readline()
print(data)# 第一行
data = f.readline()
print(data)# 第二行
f.close()
with as上下文管理器的方式: 优势是不用写close 因为会自动了close
with open('data/hello.txt', mode='r') as f:
data = f.read()
print(data)
⽂件和⽂件夹的操作
在Python中⽂件和⽂件夹的操作要借助os模块⾥⾯的相关功能,具体步骤如下:
- 导⼊os模块
import os
- ⽂件重命名 os.rename(⽬标⽂件名, 新⽂件名)
- 删除⽂件 os.remove(⽬标⽂件名)
- 创建⽂件夹 os.mkdir(⽂件夹名字)
- 删除⽂件夹 os.rmdir(⽂件夹名字)
- 获取当前⽬录 os.getcwd()
- 改变默认⽬录 os.chdir(⽬录)
- 获取⽬录列表 os.listdir(⽬录)
案例:
把code文件夹所有文件重命名 案例_xxxx
# 步骤
import os
# 1 把code文件夹所有文件重命名 案例_xxxx
dir_name = './code'
file_list = os.listdir(dir_name)
# print(file_list)
for name in file_list:
# print(name)
new_name = ' 案例_' + name
os.rename(dir_name+ '/' + name ,dir_name + '/' + new_name)