[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)
相关推荐
ZTLJQ5 小时前
数据的基石:Python中关系型数据库完全解析
开发语言·数据库·python
FreakStudio6 小时前
lvgl-micropython、lv_micropython和lv_binding_micropython到底啥关系?一文读懂
python·单片机·嵌入式·面向对象·电子diy
小江的记录本6 小时前
【Redis】Redis全方位知识体系(附《Redis常用命令速查表(完整版)》)
java·数据库·redis·后端·python·spring·缓存
dinl_vin7 小时前
Python 数据分析入门系列(一):从NumPy开始
python·数据分析·numpy
小陈工7 小时前
2026年3月26日技术资讯洞察:WebAssembly崛起、AI代码质量危机与开源安全新挑战
人工智能·python·安全·架构·开源·fastapi·wasm
2401_879693877 小时前
数据分析与科学计算
jvm·数据库·python
明月_清风8 小时前
宿命的对决:深度对比 JavaScript 与 Python 的异步进化论
后端·python
明月_清风8 小时前
别再纠结 Conda 了!2026 年,uv 才是 Python 环境管理的唯一真神
后端·python
Thomas.Sir8 小时前
第一章:Python3 基础入门:从零基础到实战精通
python·ai
telllong8 小时前
BeeWare:Python原生移动应用开发
开发语言·python