[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)
相关推荐
多恩Stone10 小时前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ40220549610 小时前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
百锦再10 小时前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
QQ51100828510 小时前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php
QQ_196328847510 小时前
Python-flask框架西山区家政服务评价系统网站设计与开发-Pycharm django
python·pycharm·flask
遥遥江上月10 小时前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
B站计算机毕业设计超人10 小时前
计算机毕业设计Django+Vue.js音乐推荐系统 音乐可视化 大数据毕业设计 (源码+文档+PPT+讲解)
大数据·vue.js·hadoop·python·spark·django·课程设计
B站_计算机毕业设计之家10 小时前
电影知识图谱推荐问答系统 | Python Django系统 Neo4j MySQL Echarts 协同过滤 大数据 人工智能 毕业设计源码(建议收藏)✅
人工智能·python·机器学习·django·毕业设计·echarts·知识图谱
计算机专业码农一枚10 小时前
Python-flask框架基于推荐算法的在线课程推荐系统设计与实现-Pycharm django
python·flask·推荐算法
ATCB10 小时前
零门槛!PythonAnywhere 免费部署全指南:不止 Django,这些项目都能搭(附主流平台对比)
后端·python·django