[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)
相关推荐
南笙北梦4 分钟前
从零写一个CAD 02:实体容器、Esc取消与键盘失灵的排查
python
硫酸锌0125 分钟前
在手机上运行Python增量备份手机数据到PC电脑
android·windows·python
沐欣工作室_lvyiyi1 小时前
家庭水资源节能系统设计(论文+源码)
c++·python·云平台·单片机毕业设计·单片机仿真·电子信息工程毕业设计·机械电子工程
FelixZhang0281 小时前
量化求真10|回测通过以后,策略就能上场吗?
人工智能·python·深度学习·学习·机器学习·金融·lstm
Ticnix1 小时前
你的 Agent 聊到第 20 轮就"失忆"?你管理的是历史,高手管理的是上下文
后端·python·agent
Raspberry_Pi_官方账号1 小时前
Raspberry Pi 官方分享:利用 14MB 的 Function-Calling LLM 实现端侧自然语言硬件控制
python·树莓派·raspberry pi
醇氧1 小时前
CentOS7.9 Yum 安装 Redis6.x(RPM 包,无需编译,推荐 remi 源)
linux·python
VidDown1 小时前
文件没问题但网页播不了:播放器接入实战与那些“环境问题
python·网络协议·音视频·视频编解码·视频
智购科技自动售货机工厂2 小时前
数字人民币硬钱包支付失败,排查发现是NFC读卡器功率不足~YH
python·面试·架构·eclipse·emacs
维克兜率天2 小时前
【维克】均值回归:跌多了会涨,涨多了会跌
开发语言·笔记·python·算法·均值算法·回归·量化