详解Python3对json和txt文件的读写操作

目录

一:Python3对txt文件的读写

        1,open打开文件

        2,读文件,read(),readline(),readlines()

         read()

        readline()

        readlines()

        3,写文件,write,writelines

        write()

        writelines()

二:Python3对json文件的读写 

 1,将字典以json格式写入到文件中

 2,读取json文件


        平时用Python的时候经常需要对文件的读写,涉及到数据处理的时候也会首选用json格式来组织结构。其实都是对文件的操作,本文将详细介绍txt和json的读写操作

一:Python3对txt文件的读写

        1,open打开文件

可以用help(open)来查看该方法的详细说明

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
    Open file and return a stream.  Raise IOError upon failure.

        主要用到的参数有file,mode,encoding,偶尔也会用到errors,比如打开文件遇到了错误怎么处理这种错误。

file:要打开的文件路径

mode:文件打开的模式

encoding:对文件进行编码或者解码的格式,常见的是utf-8

errors:有'strict'和'ignore'模式,如果要忽视文件打开过程中的错误可以用ignore

 文件打开模式的选择,r是读,w是写,a是追加写

    'r'       open for reading (default)
    'w'       open for writing, truncating the file first
    'x'       create a new file and open it for writing
    'a'       open for writing, appending to the end of the file if it exists
    'b'       binary mode
    't'       text mode (default)
    '+'       open a disk file for updating (reading and writing)
    'U'       universal newline mode (deprecated)

 代码中文件打开有两种常见写法,比如我要以读的模式打开一个test.txt文件

import os

#方法一
f1 = open(file='test.txt',mode='r',encoding='utf-8',errors='ignore')
print(f1)
f1.close()

#方法二
with open(file='test.txt',mode='r',encoding='utf-8',errors='ignore') as f2:
	print(f2)

运行结果 

<_io.TextIOWrapper name='test.txt' mode='r' encoding='utf-8'>
<_io.TextIOWrapper name='test.txt' mode='r' encoding='utf-8'> 

         with 关键字,优点是当子句体结束后文件会正确关闭,即使在某个时刻引发了异常。方法一使用完之后要记得close,close() 用来关闭文件并立即释放它使用的所有系统资源。如果你没有显式地关闭文件,Python的垃圾回收器最终将销毁该对象并为你关闭打开的文件,但这个文件可能会保持打开状态一段时间。

        文件打开拿到文件句柄后就可以进行对文件操作,其支持的属性如下所示,比较常用的有read,readline,readlines,write,writelines:

['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', '_finalizing', 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read', 'readable', 'readline', 'readlines', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'writelines']

        2,读文件,read(),readline(),readlines()

        read()

        read(size=-1, /) method of _io.TextIOWrapper instance
    Read at most n characters from stream.
    
    Read from underlying buffer until we have n characters or we hit EOF.
    If n is negative or omitted, read until EOF.

 read有一个参数,要读取的字节数,如果不写,默认就是读取全部

        readline()

 readline(size=-1, /) method of _io.TextIOWrapper instance
    Read until newline or EOF.
    
    Returns an empty string if EOF is hit immediately.

        readline方法从文件中读取整行,包括换行符'\n'。 如果 f.readline() 返回一个空的字符串,则表示已经到达了文件末尾,而空行使用 '\n' 表示,该字符串只包含一个换行符。

        我们用readline来读取一个文件,文件内容如下

who are you
i am fine
and you
me too

with open(file='test.txt',mode='r',encoding='utf-8',errors='ignore') as f2:
	print(f2.readline())
	print(f2.readline(2))
	print(f2.readline())

打印结果。其实可以好好看一下打印结果也能发现啥,readline()是从上一个读取的位置接着往下读,并且获取的一行里面会包括换行符

who are you

i 
am fine

        readlines()

readlines(hint=-1, /) method of _io.TextIOWrapper instance
    Return a list of lines from the stream.
    
    hint can be specified to control the number of lines read: no more
    lines will be read if the total size (in bytes/characters) of all
    lines so far exceeds hint.

readline方法只读取一行,readlines方法则是读取所有行,返回的是所有行组成的列表。当然readlines也有一个参数,如果不填的话就是默认读取所有行,填的话就是读取的行数

with open(file='test.txt',mode='r',encoding='utf-8',errors='ignore') as f2:
	print(f2.readlines(1))
	print(f2.readlines())

打印结果,可以看到readlines也是和readline一样从上一次readlines读取的位置开始读取

['who are you\n']
['i am fine\n', 'and you\n', 'me too\n']

        3,写文件,write,writelines

        write()

 write(text, /) method of _io.TextIOWrapper instance
    Write string to stream.
    Returns the number of characters written (which is always equal to
    the length of the string).

 write()将字符串写入到文件里

with open(file='test.txt',mode='w',encoding='utf-8',errors='ignore') as f2:
	f2.write('thank you, bob!')

        如果用'w'模式写的话,原文件有内容的话会被全部覆盖掉,上述的代码执行完之后test.txt文件里面就只有一行了。如果要保留之前的内容,就用追加写的方式,mode='a'

with open(file='test.txt',mode='a',encoding='utf-8',errors='ignore') as f2:
	f2.write('thank you, bob!')

        writelines()

writelines(lines, /) method of _io.TextIOWrapper instance

        从上面的说明中看不出来啥, 通过穿刺writelines可以接收一个列表写入,也可以写入一个字符串。这样writelines可以和readlines配合来拷贝一个文件

with open(file='test.txt',mode='a',encoding='utf-8',errors='ignore') as f2:
	f2.writelines(['thank you, bob!\n','my name is ff\n'])
	f2.writelines('end line\n')

二:Python3对json文件的读写 

 可以先看看json模块支持的方法和属性

['JSONDecodeError', 'JSONDecoder', 'JSONEncoder', '__all__', '__author__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_default_decoder', '_default_encoder', 'codecs', 'decoder', 'detect_encoding', 'dump', 'dumps', 'encoder', 'load', 'loads', 'scanner']

 常用到的方法有四个,dumps、dump、loads、load

 dumps:将python中的 字典 转换为 字符串

 loads: 将 字符串 转换为 字典

 dump: 将数据写入json文件中

 load:把文件打开,并把字符串变换为数据类型

 1,将字典以json格式写入到文件中

	def jsonWrite(infoData,jsonFile):
		with open(jsonFile, 'w', encoding='utf-8') as jsonhandle:
			jsoncontent = json.dumps(infoData, indent=4)
			jsonhandle.write(jsoncontent)

如果json中含有中文,这样显示出来就是 一堆的\u开头的数字,json文件含有中文的读写问题困扰了我好久

如果要正常显示中文,只需要在dumps中加入一个参数即可

jsoncontent = json.dumps(ruledata, indent=4, ensure_ascii=False)

2,读取json文件

with open("result.json","r") as f:
    result = json.load(f)

  • 6
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ftzchina

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值