[python]非零基础上手之文件操作

这个其实很像Node.js.

读取操作:

python 复制代码
with open ('./xx.txt', 'r', encoding = 'utf -8') as file:
for i in file:
    print(i)
#"file"是个变量, 名称自定, 参数2代表'read', 表明为读取操作.

追加操作:

属于写入的一种,不会重写文档,在原有内容后添加.

python 复制代码
with open('./xx.txt', 'a+', encoding = 'utf-8') as file:
    file.write('写入内容')

何为with:

是一种上下文管理器, with语句管理的代码块执行完毕时, 会自动关闭文件, 这是受推荐的方法,可以确保文件使用完毕后正确关闭. 当然,也可以调用文件对象的close()手动关闭:

可以在读取结构中安插try/finally结构,因为我们也不知道能不能读取成功:

python 复制代码
file = open('xx.txt', 'r')
try:
    file_content = file.read()
    print(file_content)
finally:
    file.close()

写入操作:

重写所有内容.

python 复制代码
with open('example.txt', 'w') as file:
    file.write('HelloWorld')

写入json:

需要额外模块.

python 复制代码
import json
json_file_path = 'example.json'
data = { 'name': 'John Doe', 'age': 30 }

with open(json_file_path, 'w')
json.dumps(data) # json对象转字符串

文件重命名:

python 复制代码
import os
files = os.listdir('path-to-directory') # 获取目录中文件列表
for file in files:	
    full_path = os.path.join('path-to-directoro', python
    if os.path.isfile(full_path) # 检测文件是否存在
    new_filename = 'new_name'
    os.rename(full_path, os.path.join('path_to_directory', new_filename)) # 旧路径, 新路径

逐行读文件_获取全部行:

python 复制代码
with open('file.txt', 'r') as file:
    lines = file.readlines()
    print(lines[0])

逐行读文件_获取单行:

python 复制代码
with open('file.txt', 'r') as file:
    line0 = file.readline()
    line1 = file.readline()

创建文件:

python 复制代码
import os
if not os.path.exists('./aa.txt'):
try:
    with open('./aa.txt', 'w') as file
except IOError as error:
    print (error)

创建目录:

python 复制代码
import os
if not os.path.exists('./aadir'):
try:
    os.makedirs('./aadir')
except IOError as error:
    print (error)

删除文件:

python 复制代码
import os
if os.path.isfile('./aa.txt')
try:
    os.remove('./aa.txt')
except OSError as error:
    print(error)
相关推荐
爱上纯净的蓝天2 小时前
不用云做 RAG:一个本地笔记问答工具的取舍与坑
python·开源·大模型·rag·本地部署
cspttty2 小时前
2027风险管理岗准备路线:数学与应用数学如何补齐金融、SQL与Python
开发语言·python·金融
用户8356290780512 小时前
如何使用 Python 格式化 Excel 单元格中的长文本
后端·python
我命由我123452 小时前
Python 开发 - Python 的 pathlib
java·开发语言·后端·python·学习·java-ee·学习方法
严谨的麻辣烫3 小时前
Python HTTP 连接池怎么用?从连接复用到请求异常排查
开发语言·python·http·requests·网络排查
摇滚侠3 小时前
《Java并发编程之美》第 4 章 Java 并发包中原子操作类原理剖析 阅读笔记 7
java·笔记·python
用户8356290780513 小时前
如何使用 Python 在 Word 文档中创建和格式化列表
后端·python
GIoT80103 小时前
网络出口如何选择?固定 IP 与 IP 轮换的原理及实践
python
羡林i4 小时前
ProcessPoolExecutor 传参踩坑实测:pickle 失败的四种写法
python
Dmz丶4 小时前
前端转 AI 100 天 Day 30:正式上线——从零部署一个完整服务(含 30 天复盘)
python