栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python基础——文件读写

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python基础——文件读写

文章目录
    • 文件读取
      • 文件路径
      • 整体读取
      • 逐行读取
      • 数据存储进列表
    • 写入文件
      • 写入新文件
      • 已有文件添加内容
    • json存储数据
      • dump()存储
      • load()读取

文件读取 文件路径
  • 绝对路径
  • 相对路径:相对当前文件夹下的路径

Linux与OS X采用/

dir = 'text_files/filename.txt'

Windows采用

dir = 'text_filesfilename.txt'
整体读取
#关键字with在不再需要访问文件后将其关闭
with open(dir) as file:  #打开文件
    content = file.read()
    print(content)

采用read()读取后是末尾相对原文多了一个空行,因为read()到达文件末尾时返回一个空字符串

可以采用:

print(content.rstrip())
逐行读取
with open(dir) as file:
    for line in file:
        print(line)

如果读取文件中每行都有一个/n换行符,读取时/n也会读取,会出现每次读取多一个空行,可以采用rstrip()消除

数据存储进列表
with open(dir) as file:
	lines = file.readlines()
写入文件 写入新文件

open()中:

  • 'r'为读
  • 'w'为写
  • 'a'为附加
with open(dir, 'w') as file:
    file.write('内容')
已有文件添加内容

不覆盖原有文件,而在文件后添加内容

with open(dir ,'a') as file:
	file.write('内容')
json存储数据
import json
list = [1, 2, 3, 4]
dump()存储

函数json.dump()接受两个实参:

  • 要存储的数据
  • 可用于存储数据的文件对象。
with open(dir, 'w') as file:
    json.dump(list, file)
load()读取
with open(dir) as file:
    num = json.load(file)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/300592.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号