Python轻松管理与操作文件的技巧分享
作者:小小张说故事 时间:2021-11-19 14:42:12
一、读写文件
在 Python 中,我们可以使用 open()
函数打开文件,with
语句可以自动关闭文件。
读取文件内容:
with open('example.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
写入文件:
with open('example.txt', 'w', encoding='utf-8') as f:
f.write('Hello, Python!')
二、遍历文件夹
使用 os
模块,我们可以轻松地遍历文件夹内的文件。
import os
folder_path = './example_folder'
for root, dirs, files in os.walk(folder_path):
for file in files:
print(os.path.join(root, file))
三、创建与删除文件夹
利用 os
模块,我们可以方便地创建和删除文件夹。
创建文件夹:
import os
folder_name = 'new_folder'
if not os.path.exists(folder_name):
os.makedirs(folder_name)
删除文件夹:
import shutil
folder_name = 'new_folder'
if os.path.exists(folder_name):
shutil.rmtree(folder_name)
四、文件路径操作
os.path
模块提供了很多文件路径操作的实用函数。
拼接路径:
import os
path1 = 'folder'
path2 = 'file.txt'
full_path = os.path.join(path1, path2)
print(full_path)
分割文件名和扩展名:
import os
filename = 'example.txt'
name, ext = os.path.splitext(filename)
print(name, ext)
五、总结
本文介绍了 Python 中处理文件的一些实用技巧,包括文件读写、遍历文件夹、创建与删除文件夹以及文件路径操作。掌握这些技巧,可以让你在处理文件时更加得心应手。
来源:https://juejin.cn/post/7229869537289617463
标签:Python,操作,文件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
给ubuntu18安装python3.7的详细教程
2022-11-02 16:34:57
![](https://img.aspxhome.com/file/2023/9/92399_0s.png)
说说页面中header的XHTML结构选择
2008-06-09 12:49:00
JavaScript性能优化小技巧,创建文档碎片
2010-03-31 18:27:00
Python装饰器使用示例及实际应用例子
2022-01-16 01:59:32
![](https://img.aspxhome.com/file/2023/1/82831_0s.png)
针对google Chrome的 CSS hacks
2009-11-30 12:45:00
Python3爬虫中关于中文分词的详解
2023-08-12 23:10:28
Python实现string字符串连接的方法总结【8种方式】
2023-01-07 20:52:29
uwsgi+nginx部署Django项目操作示例
2021-05-04 02:23:50
![](https://img.aspxhome.com/file/2023/5/97045_0s.png)
Anaconda的安装及其环境变量的配置详解
2022-08-31 19:21:11
![](https://img.aspxhome.com/file/2023/4/82924_0s.jpg)
python调用文字识别OCR轻松搞定验证码
2023-02-20 17:10:54
![](https://img.aspxhome.com/file/2023/4/89044_0s.png)
python argparser的具体使用
2023-07-13 09:25:36
SQL SERVER 2005中的同步复制技术
2009-01-05 13:44:00
剖析SQL Server 事务日志的收缩和截断
2009-01-15 13:04:00
关注前端开发流程
2009-12-31 17:38:00
python中随机函数random用法实例
2023-02-09 22:13:10
如何通过Python实现定时打卡小程序
2023-10-20 14:11:33
![](https://img.aspxhome.com/file/2023/9/82579_0s.png)
Python中json库的操作指南
2021-10-11 11:04:43
网站重构到底是什么
2008-11-03 11:30:00
Python中基本数据类型和常用语法归纳分享
2023-09-08 21:08:01
![](https://img.aspxhome.com/file/2023/0/98990_0s.webp)
python统计字母、空格、数字等字符个数的实例
2022-10-04 12:02:29