[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)
相关推荐
好家伙VCC4 小时前
### WebRTC技术:实时通信的革新与实现####webRTC(Web Real-TimeComm
java·前端·python·webrtc
前端玖耀里5 小时前
如何使用python的boto库和SES发送电子邮件?
python
serve the people5 小时前
python环境搭建 (十二) pydantic和pydantic-settings类型验证与解析
java·网络·python
小天源5 小时前
Error 1053 Error 1067 服务“启动后立即停止” Java / Python 程序无法后台运行 windows nssm注册器下载与报错处理
开发语言·windows·python·nssm·error 1053·error 1067
喵手5 小时前
Python爬虫实战:HTTP缓存系统深度实战 — ETag、Last-Modified与requests-cache完全指南(附SQLite持久化存储)!
爬虫·python·爬虫实战·http缓存·etag·零基础python爬虫教学·requests-cache
喵手5 小时前
Python爬虫实战:容器化与定时调度实战 - Docker + Cron + 日志轮转 + 失败重试完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·容器化·零基础python爬虫教学·csv导出·定时调度
2601_949146536 小时前
Python语音通知接口接入教程:开发者快速集成AI语音API的脚本实现
人工智能·python·语音识别
寻梦csdn6 小时前
pycharm+miniconda兼容问题
ide·python·pycharm·conda
Java面试题总结7 小时前
基于 Java 的 PDF 文本水印实现方案(iText7 示例)
java·python·pdf
不懒不懒7 小时前
【决策树算法实战指南:从原理到Python实现】
python·决策树·id3·c4.5·catr