《Python编程:从入门到实践》第十章笔记

news/2024/7/3 13:52:24 标签: python, 编程语言

10.1 从文件中读取数据

10.1.1 读取整个文件

先创建一个文件,包含精确到小数点后30位的圆周率值,且在小数点后每10位处都换行:

python">3.1415926535
  8979323846
  2643383279

下面的程序打开并读取这个文件,再将其内容显示在屏幕上:

python">with open('pi_digits.txt') as file_object:
    contents = file_object.read()
    print(contents)

函数open()接受一个参数:要打开文件的名称,Python在当前执行的文件所在目录中查找指定的文件。函数open()返回一个表示pi_digits.txt的对象,Python将这个对象存储在后面的变量file_object中。关键字with在不再需要访问文件后将其关闭,使用这种结构,可以让Python去确定在合适的时候自动将其关闭。

上面代码的输出是:

python">3.1415926535
8979323846
2643383279

read()到达文件末尾时返回一个空字符串,显示出来就是一个空行,使用rstrip()将其去除:

python">with open('pi_digits.txt') as file_object:
    contents = file_object.read()
    print(contents.rstrip())

3.1415926535
8979323846
2643383279

10.1.2 文件路径

文件路径有绝对路径和相对路径两种。相对路径的位置是相对于当前运行的程序所在目录,例如,假设程序文件存储在文件夹Python_work中,文本文件存储在文件夹Python_work的子文件夹text_files中,相对路径可编写为:

python">## Linux 和 OS X
with open('text_files/filename.txt') as file_object:
## Windows
with open('text_files\filename.txt') as file_object:

绝对路径指的是向Python传递一个完整的文件路径。

10.1.3 逐行读取

使用for循环以每次一行的方式检查文件:

python">with open('pi_digits.txt') as file_object:
    for line in file_object:
        print(line)

3.1415926535

8979323846

2643383279

出现空白行的原因是每一行末尾都有一个换行符,而print语句也会加上一个换行符,在print语句中使用rstrip()来消除空白行:

python">with open('pi_digits.txt') as file_object:
    for line in file_object:
        print(line.rstrip())

3.1415926535
8979323846
2643383279

10.1.4 创建一个包含文件各行内容的列表

要在with代码块外访问文件的内容,可在with代码块内使用方法readlines()将文件的各行存储在一个列表中:

python">with open('pi_digits.txt') as file_object:
    lines = file_object.readlines()
for line in lines:
    print(line.rstrip())

10.1.5 使用文件的内容

使用读取上述文件中的数字,使它们之间没有空格:

python">with open('pi_digits.txt') as file_object:
    lines = file_object.readlines()
pi_string = ""
for line in lines:
    pi_string += line.rstrip()

print(pi_string)
print(len(pi_string))

10.1.6 包含一百万位的大型文件

略。

10.1.7 圆周率值中包含你的生日吗

略。

10.2 写入文件

10.2.1 写入空文件

python">filename = 'programming.txt'

with open(filename,'w') as file_object:
    file_object.write("I love programming.")

第二个实参‘w’表示要以写入模式打开文件,类似的模式有读取模式('r‘),附加模式(’a‘)或能让你能够读取和写入文件的模式(’r+‘),如果忽略,Python将以默认的只读模式打开文件。以(’w‘)模式打开文件时,如果指定的文件已经存在,Python将在返回文件对象前清空该文件。
注意:Python只能将字符串写入文件,要将数值数据存储到文本文件,必须先使用函数str()将其转换为字符串格式。

10.2.2 写入多行

python">filename = 'programming,txt'
with open(filename,'w') as file_object:
	file_object.write("123\n")
	file_object.write("456\n")

10.2.3 附加到文件

以附加模式’a‘打开文件时,不会清空文件内容,写入文件的行都将添加到文件末尾,如果指定文件不存在,创建文件。

python">with open(filename,'a') as file_object:
	file_object.write("123\n")

10.3 异常

Python使用被称为异常的特殊对象来管理执行程序期间发生的错误,异常是使用try-except代码块处理的。

10.3.1 处理ZeroDivisionError异常

python">>>> 5/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

10.3.2 使用try-except代码块

python">>>> try:
...    print(5/0)
... except ZeroDivisionError:
...    print("You can't divide by zero!")
...
You can't divide by zero!

10.3.3 使用异常避免崩溃

10.3.4 else代码块

python">while True:
	first_number = input("\nFirst number:")
	if first_number == 'q':
		break
	second_number == input("Second number:")
	try:
		answer = int(first_number) / int(second_number)
	except ZeroDivisionError:
		print("You can't divide by 0!")
	else:
		print(answer)

First number:5
Second number:0
You can't divide by 0!

First number:5
Second number:2
2.5

First number:q

10.3.5 处理FlieNotFoundError异常

python">try:
	with open(filename) as f_obj:
		contents = f_obj.read()
except FileNotFoundError:
	msg = "Sorry,the file" + filename + "does not exist"
	print(msg)

10.3.6 分析文本

统计文件中单词的个数,可以用split()方法。

python">>>> title = "Alice in Wonderland"
>>> title.split()
['Alice', 'in', 'Wonderland']
>>> len(title.split())
3

10.4 存储数据

模块json让你能够将简单的Python数据结构转储到文件中,并在程序再次运行时加载文件中的数据。

10.4.1 使用json.dump()和json.load()

使用函数json.dump()将数字列表存储到文件numbers.json中。

python">import json
numbers = [2,3,5,7,11]
filename = 'numbers.json'
with open(filename,'w') as f_obj:
    json.dump(numbers,f_obj)

再编写一个程序,使用json.load()读取numbers.json中的信息,存储到numbers变量中,打印输出:

python">import json
filename = 'numbers.json'
with open(filename,'r') as f_obj:
    numbers = json.load(f_obj)

print(numbers) 

[2, 3, 5, 7, 11]

http://www.niftyadmin.cn/n/1701548.html

相关文章

Citrx XenDesktop 7 实施二 安装XenServer

安装XenServer. XenServer 是基本,虽然,我们可以把XenDesktop 安装在ESXI和Hyper-V上面.但是,兼容性还有便捷性,都没有在XenServer上面好.所以,虽然我自己也很不喜欢XenServer.但是,考虑到这些.还是老老实实的安装吧.1.说心里话,我最不想写的就是关于系统安装之类的东西.觉得特…

Python之路,Day26-----暂无正在更新中

Python之路,Day26-----暂无正在更新中 转载于:https://www.cnblogs.com/weiman3389/p/6222631.html

利用正则过滤各种标签,空格,换行符的代码

收集php利用正则过滤各种标签&#xff0c;空格&#xff0c;换行符的代码&#xff1a; 查看代码 打印01$strpreg_replace("/\s/", " ", $str); //过滤多余回车02$strpreg_replace("/<[ ]/si","<",$str); //过滤<__("<…

1160. 拼写单词(简单)- LeetCode

题目描述 自己解法 由题意可知&#xff0c;字母的顺序并不重要&#xff0c;只需要比较词汇表每个字符串中的每个字符的数目与字母表中字符的数目即可&#xff0c;使用哈希表即可求解&#xff0c; Python3代码&#xff1a; class Solution:def countCharacters(self, words: L…

JDBC数据库连接池技术

在JDBC中&#xff0c;获得连接或释放资源是非常消耗系统资源的两个过程&#xff0c;为了解决此类性能问题&#xff0c;通常采用连接池技术&#xff0c;来共享连接。这样我们就不需要每次都创建连接、释放连接了&#xff0c;这些操作都交给了连接池。 用池的概念来管理Connectio…

Python - all()函数

all() 函数用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE&#xff0c;如果是返回 True&#xff0c;否则返回 False。元素除了是 0、空、None、False 外都算 True&#xff0c;输入参数为元组或列表&#xff0c;函数等价于&#xff1a; def all(iterable):for e…

【运维囧事】NTP服务器引发的一场血案

8月份&#xff0c;加入了一个新的项目组&#xff0c;电网项目组。到了项目第二天&#xff0c;便被要求做一个时间同步服务器&#xff0c;将集群内的服务器全都时间同步&#xff0c;因为集群内服务器总会差个几秒钟&#xff0c;影响数据的一致性。这个很简单&#xff0c;我们的使…

118.杨辉三角(简单)- LeetCode

题目描述 自己解法 运用动态规划思想&#xff0c;当前层下标0、-1的元素值为1&#xff0c;下标从1到len(res)-1的元素中&#xff0c;若下标为i&#xff0c;其值等于上一层下标[i]、[i-1]的元素之和&#xff0c;Python实现&#xff1a; class Solution:def generate(self, num…