3. Python 输出,读写文件#
3.1. print 函数输出#
Python 输出非常方便,用print()
函数,小括号里面可以是数字、字符串、列表、字典等类型。
print([12, 45, 69]) # 列表
[12, 45, 69]
print({"name": "chen", "mark": 85}) # 字典
{'name': 'chen', 'mark': 85}
也可以把字符串跟变量一起放到print
函数里面输出
a = [1, 2, 3]
b = 4
print("a = ", a, ",b = ", b)
a = [1, 2, 3] ,b = 4
print 默认输出后光标换行:
a = "zhang"
age = 25
print("my name is %s" % a) # 光标换行了
print("age is %d" % age)
my name is zhang
age is 25
若要更改 print 光标结尾的内容,可以通过end
参数更改:
a = "zhang"
age = 25
print("my name is %s" % a, end="-")
print("age is %d" % age)
my name is zhang-age is 25
若要在一个 print 语句中输出多个变量,可以将多个变量放在一个元组 (tuple) 里:
a = "zhang"
age = 25
print("my name is %s and I am %d years old." % (a, age))
my name is zhang and I am 25 years old.
3.2. f 函数输出#
输出也可以用 f{expression}
,大括号中的 exression 可以是一个变量名,例如,下面的代码打印出一个数组列表:
a = [1, 2, 3]
print(f"the array is {a}") # 输出列表 a
the array is [1, 2, 3]
b = 3.2
print(f"the array is {a}, the numer is {b}")
the array is [1, 2, 3], the numer is 3.2
import math
b = 4.56
print(f"the numbers are {math.pi} and {b}")
the numbers are 3.141592653589793 and 4.56
也可以结合冒号:
指定保留的小数位数,结合等号=
实现等号赋值的表达。例如
冒号后面的格式具体为:
: <填充><对齐><宽度><.><精度><变量类型> |
---|
常见的对齐代码有:
代码 |
含义 |
---|---|
> |
右对齐,默认 |
< |
左对齐 |
^ |
居中对齐 |
常见的变量类型代码有:
代码 |
含义 |
---|---|
s |
输出字符串形式,默认形式 |
d |
输出整数的十进制 |
b |
输出整数的二进制 |
f |
输出浮点数的标准浮点形式 |
e |
输出浮点数的科学表示形式 |
% |
输出浮点数的百分形式 |
a = 1
b = 4.56
# 第一个数保留 3 位小数,浮点型,第二个数右对齐,宽度 20,保留 2 位小数,百分数显示
f"the numbers are {a:.3f} and {b = :>20.2%}"
'the numbers are 1.000 and b = 456.00%'
a = 5.6
print(f"{a = :+^10.2f}") # 用+填充,居中对齐,宽度为 10,保留两位小数
a = +++5.60+++
Note
填充,对齐,宽度,精度,变量类型本身也可以作为变量
a = 5.6
fill = "*"
print(f"{a = :{fill}^10.2f}") # 用+填充,居中对齐,宽度为 10,保留两位小数
a = ***5.60***
3.3. 用 format 格式化输出#
用format
也可以实现多种格式化输出,它的基本用法为:
包含{}的string.format(value1, value2...) |
---|
在字符串 string 中,用大括号{}
表示变量在输出时所在的位置。
a = 3
b = 4.56
print("the numbers are {} and {:.3f}".format(a, b))
the numbers are 3 and 4.560
大括号{}
中可以跟一个表示变量的位置索引的数字。
a = 3
b = 4.56
print("the numbers are {1} and {0}".format(a, b)) # 指定了变量的 print 位置
print("the numbers are {0} and {1}".format(a, b))
print("the numbers are {0} and {1} and {0}".format(a, b))
the numbers are 4.56 and 3
the numbers are 3 and 4.56
the numbers are 3 and 4.56 and 3
要输出大括号符号,则用两个大括号表示:
print("the numbers are {{ {0} }} and {{ {1} }}".format(a, b))
the numbers are { 3 } and { 4.56 }
使用format
时,在大括号{}
中,可以通过冒号:
以及其他参数,实现一些格式化输出。具体为:
<变量位置索引> : <填充><对齐><宽度><.><精度><变量类型>} |
---|
a = 3
b = 4.56
print("the numbers are {0:10.2f} and {0:.3%}".format(a, b)) # print 小数和百分数
the numbers are 3.00 and 300.000%
a = 123456
print("the numer is {:e}".format(a)) # print 科学计数格式
the numer is 1.234560e+05
一些例子:
a = 5
print("a = {:0>5d}".format(a)) # 用零填充左边, 宽度为5
a = 00005
a = 5
print("a = {:<4d}".format(a)) # 填充右边, 默认采用空格填充,宽度为 4
a = 5
a = 5.6
print("a = {:+^10.2f}".format(a)) # 用+填充,居中对齐,宽度为 10,保留两位小数
a = +++5.60+++
宽度值以及精读值可以作为变量,用大括号 {} 结合参数传递的形式赋值,例如:
a = 5.6
print("a = {:^{width}.{precision}f}".format(a, width=10, precision=3)) # 宽度与精度值作为变量
a = 5.600
3.4. 用 % 格式化输出#
若要格式化输出,要用到百分号 %,语法规则类似 c 语言,具体参考下面的例子。
import math
print("the number is %d" % math.pi) # 按照整数 print
the number is 3
print("the number is %.2f" % math.pi) # 按照浮点数 print,并保留 2 位小数
the number is 3.14
print("the number is %.2f\n" % math.pi) # \n 表示 print 后光标换行
the number is 3.14
b = 4.56
print("the numbers are %.2f and %d" % (math.pi, b)) # 同时 print 多个数据
the numbers are 3.14 and 4
print("the number is %5.2f" % math.pi) # 按照浮点数 print,保留 2 位小数,并且输出内容的宽度为5个字符
the number is 3.14
print("the number is %s" % 321) # 按照字符串 print
the number is 321
print("%.1f%%" % b) # 百分比输出,并保留一位小数
4.6%
引号里面的百分号 % 定义了输出数据的格式,%d 表示按整数类型输出, %.2f 表示按浮点型输出,其中小数点后的数字表示保留几位小数,小数点前的数字表示输出变量所占的字符宽度,%s 表示按字符串输出,%.1f%% 表示按百分比输出,并保留一位小数。同时 print()函数里面还用一个百分号 % 分割 print 内容与数据变量,多个数据变量可以在小括号里面。
3.5. 读写文件#
Python 对文本文件的操作步骤为打开——操作——关闭
:打开计算机存储位置的一个文件,进行一些读写操作,然后关闭这个文件。打开后的文件处于占用状态,此时计算机的其他进程不能操作这个文件;文件关闭后,其他进程才能操作这个文件。
Python 用open()
函数打开一个文件对象,常用的语法规则为:
open 语句的一般模式 | |
---|---|
filename | 字符串,文件地址及文件名,默认地址为当前的项目文件夹 |
mode | 文件读写模式,默认模式为只读(r) |
常见的文件读写模式(mode)有:
r | 以只读方式打开文件,从文件内容开头读取,这是默认模式 |
w | 打开一个文件只用于写入,从文件内容开头写入,即原有内容会被删除; |
如果该文件不存在,创建新文件 | |
w+ | 打开一个文件用于读写,从文件内容开头写入,即原有内容会被删除; |
如果该文件不存在,创建新文件 | |
r+ | 打开一个文件用于读写。文件指针将会放在文件的开头 |
a | 打开一个文件用于追加写入,如果该文件已存在,从文件结尾写入; |
如果该文件不存在,创建新文件进行写入 | |
a+ | 打开一个文件用于追加读写,如果该文件已存在,从文件结尾写; |
如果该文件不存在,创建新文件进行写入 |
上面几个读写模式的详细比较如下面的表格所示:
模式 |
r |
r+ |
w |
w+ |
a |
a+ |
---|---|---|---|---|---|---|
读 |
✓ |
✓ |
✓ |
✓ |
||
写 |
✓ |
✓ |
✓ |
✓ |
✓ |
|
创建 |
✓ |
✓ |
✓ |
✓ |
||
覆盖 |
✓ |
✓ |
||||
从文件开始操作 |
✓ |
✓ |
✓ |
✓ |
||
在文件末尾操作 |
✓ |
✓ |
举例:
f = open(
"test.txt", "w"
) # 在当前文件夹下新建文件,若要在指定位置 E 盘 files 文件夹下打开文件 f = open('E:\\files\\test.txt', 'r')
f.write("my name is zhang san\nhis name is li si") # 书写内容,用 \n 换行
f.close() # 关闭打开的文件
上面的程序在当前目录新建了一个 txt 文件。 通过write()
函数在文件里面写内容,其中,\n 表示换行。若要在指定地址内创建和修改文件,可以进一步在 filename 中添加文件地址字符串。
下面通过read()
函数读取文件里的全部内容,并返回一个字符串:
f = open("test.txt", "r")
str = f.read() # 读取文件内容
print(str) # 将内容输出到屏幕
f.close() # 关闭打开的文件
my name is zhang san
his name is li si
如果只读取一行,可以用readline()
函数,另外可以用readlines()
函数读取所有行,并返回一个每行作为元素的列表。
在实际的 python 读写文件中,经常用到的是with-open
语句。由于文件读写时可能产生读写 IOError,一旦出错,后面的 f.close() 就不会调用,导致文件在后台一直没有关闭,用 with-open
语句可以省略 f.close() 语句。上面的读写代码也可以变为:
# 写文件
with open("test.txt", "w") as f:
f.write("my name is zhang san\nhis name is li si")
# 读文件
with open("test.txt", "r") as f:
str = f.read() # 读取文件内容
print(str) # 将内容输出到屏幕
my name is zhang san
his name is li si
读写数据格式的文件,例如 txt, xls, xlsx, csv 文件等,一般使用工具包Pandas
读取文件并处理数据,读者可以在本书的Pandas
章节查阅。读写 word 格式文件,可以使用工具包textract
,docx2txt
等,本书不再赘述,感兴趣的读者可以在网上查阅相关资料。
3.6. os
, sys
模块#
3.6.1. os
模块#
Python 中的 os
模块是用于与操作系统交互的标准库,提供了处理文件、目录、进程和环境变量等功能。以下是 os
模块的一些主要功能和用法:
import os
print(os.name) # 获取操作系统名称,'posix' (Linux/macOS) 或 'nt' (Windows)
print(os.getcwd()) # 获取当前工作目录
print(os.listdir()) # 获取当前目录下的文件和文件夹列表
切换目录
os.chdir('/path/to/directory') # 更改当前工作目录到新地址 '/path/to/directory'
创建和删除目录
import os
os.mkdir('new_dir') # 创建一个新目录
os.makedirs('parent/child/grandchild') # 递归创建目录
os.rmdir('new_dir') # 删除目录(目录必须为空)
os.removedirs('parent/child/grandchild') # 递归删除空目录
文件操作
import os
file_path = "new_file.txt" # 新建文件
with open(file_path, "w") as f:
f.write("Hello, this is a new file!") # 写入内容
os.rename('new_file.txt', 'new_file2.txt') # 重命名文件或目录
os.remove('new_file2.txt') # 删除文件
环境变量
print(os.environ) # 获取所有环境变量
print(os.environ.get('HOME')) # 获取特定环境变量
os.environ['NEW_VAR'] = 'Hello' # 设置新的环境变量
路径处理
import os.path
print(os.path.abspath('file.txt')) # 获取文件的绝对路径
print(os.path.dirname('file.txt')) # 获取文件所在目录名
print(os.path.join('dir', 'file.txt')) # 组合路径
print(os.path.exists('file.txt')) # 检查路径是否存在
print(os.path.isfile('file.txt')) # 检查是否是文件
print(os.path.isdir('dir')) # 检查是否是目录
print(os.path.splitext('file.txt')) # 拆分文件扩展名
print(os.path.basename('/path/to/file.txt')) # 获取文件名
得到当前 .py 文件的名字
import os
# 获取当前文件的路径
current_file_path = __file__
# 提取文件名
current_file_name = os.path.basename(current_file_path)
如果脚本文件名为 example.py,那么输出将会是
当前文件名: example.py
Note
Python 可以使用__file__
属性来获取当前 .py 文件的路径。
进程管理
import os
print(os.getpid()) # 获取当前进程ID
print(os.getppid()) # 获取父进程ID
7254
7165
跨平台操作
import os
if os.name == 'nt': # Windows
print("Running on Windows")
elif os.name == 'posix': # Linux/macOS
print("Running on Linux or macOS")
Running on Linux or macOS
3.6.2. sys
模块#
sys
模块提供了一些与 Python 解释器及其环境相关的变量和函数,适用于处理命令行参数、运行时环境、标准输入输出等。
获取 Python 版本
import sys
print(sys.version) # 获取 Python 版本
print(sys.version_info) # 获取详细的版本信息
3.12.2 | packaged by conda-forge | (main, Feb 16 2024, 20:54:21) [Clang 16.0.6 ]
sys.version_info(major=3, minor=12, micro=2, releaselevel='final', serial=0)
获取当前系统信息
print(sys.platform) # 获取操作系统类型 ('win32', 'linux', 'darwin' 等)
darwin
获取 Python 模块搜索路径
print(sys.path) # 获取模块搜索路径
sys.path.append("/my/custom/path") # 添加自定义路径
3.7. 练习#
Exercise 3.1
格式化输出 0.0003278 对应的科学计数形式,保留4位有效数字,并且为百分形式。
Solution to Exercise 3.1
print("{:.4%}".format(0.0003278))
Exercise 3.2
将下面文字输入到电脑的一个 txt 文件中,并读取将内容显示在屏幕上:
话说天下大势,分久必合,合久必分:周末七国分争,并入于秦;及秦灭之后,楚、汉分争,又并入于汉;汉朝自高祖斩白蛇而起义,一统天下,后来光武中兴,传至献帝,遂分为三国。
Solution to Exercise 3.2
with open("./text.txt", "w") as f:
f.write('话说天下大势,分久必合,合久必分:周末七国分争,并入于秦;及秦灭之后,楚、汉分争,又并入于汉;\
汉朝自高祖斩白蛇而起义,一统天下,后来光武中兴,传至献帝,遂分为三国。')
# 读文件
with open ("./text.txt", "r") as f:
str = f.read() # 读取文件内容
print(str) # 将内容输出到屏幕