一、文件管理
1、打开
文件句柄 = open('文件路径', '模式',编码方式),此处编码方式一般默认就好。
在桌面新建文件夹,路径为C:\Users\administered\Desktop\nwe_tesxt.txt
输入命令打开:
f=open(file='C:\Users\administered\Desktop\nwe_tesxt.txt',mode='w')

在路径前面加r,即保持字符原始值的意思。
f=open(file=r'C:\Users\administered\Desktop\nwe_tesxt.txt',mode='w')
替换为双反斜杠
f=open(file='C:\\Users\\administered\\Desktop\\nwe_tesxt.txt',mode='w')
替换为正斜杠
f=open(file='C:/Users/administered/Desktop/nwe_tesxt.txt',mode='w')
2、在文件中写入内容
f = open(file='C:/Users/administered/Desktop/nwe_tesxt.txt',mode='w')
f.write('hello world, i am here!')
f.close()
3、在文件中读取(所有)内容
f = open(file='C:/Users/administered/Desktop/nwe_tesxt.txt',mode='r')
content=f.readlines() #读取所有数据,并归为一个列表,每一行为一个元素,需要将结果储存起来
i=1
for temp in content:
print(f'第{i}行的内容是:{temp}')
i+=1
f.close()
4、文件重命名
导入模块:import os
第一步:os.listdir(os.getcwd())

第二步:os.rename('new_text.txt','nwe_tesxt.txt')

修改完毕。
5、获取文件路径
python - OS(一)获取绝对路径 - 深圳-逸遥 - 博客园
导入模块:from os.path import *
第一步: 获取当前目录或文件的绝对路径
dir_path = dirname(abspath('nwe_tesxt.txt'))
print(f'当前文件所在目录的绝对路径为:{dir_path}')
dir_path_new=os.path.abspath('nwe_tesxt.txt')
print(f'当前文件的绝对路径为:{dir_path_new}')

简化版:只能获取当前文件路径
导入模块:
import os
获取当前文件的绝对路径:
os.getcwd()
6、改变默认目录
#使用函数, 路径的具体写法参照前面的三种修改方式r'','\\','/'。
os.chdir("path")
#重新获取目标列表,确认路径已更改
os.listdir(os.getcwd())

7.删除文件夹
空目录的删除:https://zixuephp.net/manual-python3-1617.html
递归删除:Python 递归删除非空目录(包括子目录以及文件)_dev_zyx的博客-CSDN博客
import os
os.rmdir("")
8.删除文件
os.chdir(r'C:\Users\administered\Desktop') #选择父目录
os.mkdir('new_files') #创建文件夹
os.chdir(r'C:\Users\administered\Desktop\new_files') #重新选择路径
os.remove('del.txt') #删除文件
os.listdir() #检查文件是否删除

9.批量修改文件夹中文件的名字
#改变默认目录
os.chdir()
#输入修改的文件夹名字(也可以直接赋值)
path=input('')
#获取文件夹文件列表
path_now=os.getcwd()
file_name_now=os.listdir(path_now)
#创建循环,逐个更改用户名:
for sub_pathname in file_name_now:
nwe_file_name='文件'+sub_pathname
os.rename(sub_pathname,nwe_file_name)
#确认文件名字批量修改成功
os.listdir(os.getcwd())

网友评论