python基础——文件读写

文件读取

文件路径

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

Linux与OS X采用/

dir = 'text_files/filename.txt'

Windows采用\

dir = 'text_files\filename.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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值