python学习笔记-8. python的输入和输出
文章目录
- python学习笔记-8. python的输入和输出
- 前言
- 一、字面量打印与格式化
- 1. 字面量定义
- 2. 字面量插值
- 二、文件读取
- 1. open函数
- 三、json格式转换
- 1. json概念
- 2. json的使用
- 总结
前言
一、字面量打印与格式化
1. 字面量定义
字面量是以变量或常量给出的原始数据,在程序中可以直接使用字面量
理解:
a = 1,1就是字面量
a = “test”,test就是字面量
a = True,True就是字面量
变量的值,就可以理解为字面量,不过通常是把字面量赋给变量,然后调用变量来使用的
字面量类型:
- 数值型
- 字符型
- 布尔型
- 字面量集合:列表、元祖、集合、字典
- 特殊字面量
2. 字面量插值
字面量插值就是将变量、常量以及表达式插入的一种技术,可以避免字符串拼接问题
字面量插值方法:
- 格式化输出
- 通过string.format()方法拼接
- 通过F-strings拼接
使用%进行格式化输出
# 使用%进行格式化输出
name = "message"
str = "this is %s test %d"%(name, 20)
print(str)
# float类型,.2代表保留2位小数
pi = "%.2f"%3.1415926
print(pi)
使用format()方法
listdata = ['test1','test2']
dictdata = {"name":"testname","passwd":"123456"}
print("this is test {}".format('message'))
print("this is {0} test {1}".format(*listdata))
print("this is {name}, message is {passwd}".format(**dictdata))
使用f-strings拼接
# 使用方法:f'{paramname}',paraname为定义的变量名,如下
name = "test"
print(f'my name is {name}')
# {}中可以使用变量方法
print(f'my name is {name.upper()}')
# {}中也可以使用表达式
print(f'my age is {10+3}')
# {}中使用\是不合法的
二、文件读取
文件读取是常见的IO操作,操作IO使用操作系统提供的能力,操作系统是不允许普通程序直接操作磁盘的,所以读写文件需要请求操作系统打开一个对象,也就是我们程序中要操作的文件对象。
文件读写的步骤如下:
- 打开文件,获取文件描述符
- 操作文件描述符
- 关闭文件
1. open函数
定义:open(file, mode=‘r’, buffering=None, encoding=None, errors=None, newline=None, closefd=True)
def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): # known special case of open
"""
Open file and return a stream. Raise OSError upon failure.
file is either a text or byte string giving the name (and the path
if the file isn't in the current working directory) of the file to
be opened or an integer file descriptor of the file to be
wrapped. (If a file descriptor is given, it is closed when the
returned I/O object is closed, unless closefd is set to False.)
mode is an optional string that specifies the mode in which the file
is opened. It defaults to 'r' which means open for reading in text
mode. Other common values are 'w' for writing (truncating the file if
it already exists), 'x' for creating and writing to a new file, and
'a' for appending (which on some Unix systems, means that all writes
append to the end of the file regardless of the current seek position).
In text mode, if encoding is not specified the encoding used is platform
dependent: locale.getpreferredencoding(False) is called to get the
current locale encoding. (For reading and writing raw bytes use binary
mode and leave encoding unspecified.) The available modes are:
========= ===============================================================
Character Meaning
--------- ---------------------------------------------------------------
'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)
========= ===============================================================
The default mode is 'rt' (open for reading text). For binary random
access, the mode 'w+b' opens and truncates the file to 0 bytes, while
'r+b' opens the file without truncation. The 'x' mode implies 'w' and
raises an `FileExistsError` if the file already exists.
Python distinguishes between files opened in binary and text modes,
even when the underlying operating system doesn't. Files opened in
binary mode (appending 'b' to the mode argument) return contents as
bytes objects without any decoding. In text mode (the default, or when
't' is appended to the mode argument), the contents of the file are
returned as strings, the bytes having been first decoded using a
platform-dependent encoding or using the specified encoding if given.
'U' mode is deprecated and will raise an exception in future versions
of Python. It has no effect in Python 3. Use newline to control
universal newlines mode.
buffering is an optional integer used to set the buffering policy.
Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
line buffering (only usable in text mode), and an integer > 1 to indicate
the size of a fixed-size chunk buffer. When no buffering argument is
given, the default buffering policy works as follows:
* Binary files are buffered in fixed-size chunks; the size of the buffer
is chosen using a heuristic trying to determine the underlying device's
"block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
On many systems, the buffer will typically be 4096 or 8192 bytes long.
* "Interactive" text files (files for which isatty() returns True)
use line buffering. Other text files use the policy described above
for binary files.
encoding is the name of the encoding used to decode or encode the
file. This should only be used in text mode. The default encoding is
platform dependent, but any encoding supported by Python can be
passed. See the codecs module for the list of supported encodings.
errors is an optional string that specifies how encoding errors are to
be handled---this argument should not be used in binary mode. Pass
'strict' to raise a ValueError exception if there is an encoding error
(the default of None has the same effect), or pass 'ignore' to ignore
errors. (Note that ignoring encoding errors can lead to data loss.)
See the documentation for codecs.register or run 'help(codecs.Codec)'
for a list of the permitted encoding error strings.
newline controls how universal newlines works (it only applies to text
mode). It can be None, '', '\n', '\r', and '\r\n'. It works as
follows:
* On input, if newline is None, universal newlines mode is
enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
these are translated into '\n' before being returned to the
caller. If it is '', universal newline mode is enabled, but line
endings are returned to the caller untranslated. If it has any of
the other legal values, input lines are only terminated by the given
string, and the line ending is returned to the caller untranslated.
* On output, if newline is None, any '\n' characters written are
translated to the system default line separator, os.linesep. If
newline is '' or '\n', no translation takes place. If newline is any
of the other legal values, any '\n' characters written are translated
to the given string.
If closefd is False, the underlying file descriptor will be kept open
when the file is closed. This does not work when a file name is given
and must be True in that case.
A custom opener can be used by passing a callable as *opener*. The
underlying file descriptor for the file object is then obtained by
calling *opener* with (*file*, *flags*). *opener* must return an open
file descriptor (passing os.open as *opener* results in functionality
similar to passing None).
open() returns a file object whose type depends on the mode, and
through which the standard file operations such as reading and writing
are performed. When open() is used to open a file in a text mode ('w',
'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
a file in a binary mode, the returned class varies: in read binary
mode, it returns a BufferedReader; in write binary and append binary
modes, it returns a BufferedWriter, and in read/write mode, it returns
a BufferedRandom.
It is also possible to use a string or bytearray as a file for both
reading and writing. For strings StringIO can be used like a file
opened in a text mode, and for bytes a BytesIO can be used like a file
opened in a binary mode.
"""
pass
参数:
注:通常关注前2个参数即可
- file :为提供文件名称/文件路径的文本或字符串
- mode: 文件的打开模式,常用的有r(只读)、w(写)、x(创建写入)、a(追加)
- buffering: 缓冲机制
- encoding:默认使用系统编码,也可使用其它编码
- errors:指定编码错误的方式,可选
- newline:控制换行的方式
- closefd:为False时,文件关闭,描述符会保持打开状态,如果给定文件名,则必须为True
实例:
项目根目录下创建文件test.txt,内容为:
this is test message
this is test message1
注:默认路径为项目根目录,根目录下创建文件,file参数可以直接使用’filename’,在项目其他目录则使用’/data/filename’方式,非项目下文件则使用绝对路径’/usr/local/test.txt’
# 使用open打开文件,test.txt在根目录下,所以直接使用文件名就好了
"""
mode参数:
r:只读
w:写入
x:执行
a:追加
b:二进制
t:文本方式
+;读写
"""
f = open('test', 'rt')
# 使用read方法,读取数据流内容,读取所有文件
print(f.read())
# 使用readline()方法,读取单行数据
print(f.readline())
# 使用readlines()方法,读取所有数据,返回以行为元素的列表
print(f.readlines())
# 使用readable()方法判断文件是否可读
print(f.readable())
# 使用close关闭文件流
f.close()
# 使用with关键字进行打开文件,实现文件流的自动关闭
with open('test', 'rt') as f:
print(f.read())
三、json格式转换
1. json概念
json是一种数据交换格式,易于读写,易于解析和生成,json是有列表和字典组成的
使用场景:
- 生成:将对象生成为字符串,用于持久化,网络传输等
- 解析:解析来自文件、数据库、网络传输的字符串或python对象
- 数据交换:跨语言的数据交换
2. json的使用
code中直接import导入json即可
import json
json的常用方法
import json
# 1. dumps(python obj) 把json串(列表类型)转换为字符串类型
json_test = [{
"name": "test",
"age": 15
}, {
"name": "test1",
"age": 16
}]
# dumps参数 json变量名,sort_keys按照key排序,indent以缩进的方式进行输出
data = json.dumps(json_test, sort_keys=True, indent=4)
print(data)
print(type(json_test))
print(type(data))
# 2. loads(json_string) 把字符串转换为json
str = '''
[{
"name": "test",
"age": 15
}, {
"name": "test1",
"age": 16
}]
'''
print(type(str))
json_test1 = json.loads(str)
print(type(json_test1))
print(json_test1)
# 3. dump() 把数据类型转换为字符串并存储在文件中
json_test2 = [{
"name": "test",
"age": 15
}, {
"name": "test1",
"age": 16
}]
json.dump(json_test2, open('test', 'w'))
# 4. load(file_name) 把文件打开,把文件内容转换为json格式
json_test3 = json.load(open('test', 'r'))
print(json_test3)
print(type(json_test3))
# 按照列表函数可以进行操作
print(json_test3[0]['name'])
总结
重点:
字面量插值–%格式化输出、format、f’str’
文件操作:open函数、文件流函数read、readline、readlines、with关键字
json函数:dumps、dump、loads、load