[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)
相关推荐
维爱智VR认知学能6 分钟前
VR抗干扰训练调度器:视听干扰等级分层注入与安全上限熔断实现
python·软件工程·架构设计
prince_zxill1 小时前
百度 Unlimited-SVG:1024 个 token 看懂整张图,0.5B 参数把它写成 SVG 代码
python·百度·svg·多模态·图像转矢量
zc.z2 小时前
Context Engineering:深度学习知识点
python·prompt·上下文工程
5G微创业3 小时前
短视频去水印接口怎么对接?一篇讲清 GET 参数、返回字段与多语言示例
python·小程序·api·短视频·去水印
布语world3 小时前
某东pc滑块分析
前端·javascript·网络·python·安全
m0_646429973 小时前
Python pytest 单元测试基础
python
DeepVisionary4 小时前
从1秒多压到0.39秒,Gemini 4 Live靠先应声再干活,把语音延迟降了3倍
python·自动化
Web3&Basketball4 小时前
Playwright实战:27B网页智能体评测3步
python·大模型·浏览器自动化·playwright·网页智能体·评测口径·molmoweb
zc.z4 小时前
RAG (一):从底层原理、Naive RAG 到企业级项目开发与面试实战
人工智能·python·rag
王者鳜錸4 小时前
【中英】-Android离线语音听写-讯飞 AIKit源码实现
开发语言·python·智能手机·安卓·离线中英识别