读取整个文件
3.1415926535
8979323846
2643383279
with open ('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
- 调用open()打开文件,函数open接受一个参数:要打开文件的名称。
- Python在当前执行的文件所在目录中查找指定文件。
- 函数open()返回一个表示文件的对象,并将这个对象存储到变量file_object中
- 关键字with在不再需要访问文件后将其关闭
- 可以调用open()和close()来打开和关闭文件,但,如果程序存在bug,文件将不能正常关闭,导致数据丢失或受损,也可能过早的关闭文件,导致无法访问
- 该with让python确定,只管打开文件,并在需要时使用它,Python自会在合适的时候自动将其关闭。

- 该输出末尾多了一个空行
- 因为read()到达问价末尾时返回一个空字符串,而降空字符串显示出来时就是一个空行
- 要删除多出来的空行,在print()语句中使用rstrip()
print(contents.rstrip())
文件路径
- 当读取文件.txt与.py程序文件不在同一目录下,需要提供文件路径,它让Python到系统的特定位置中查找
- 使用相对文件路劲来打开读取文件
- 其中Linux和OSX中,路径需要斜杠(/)
- 在Windows中使用反斜杠(\)
with open('Python_work\pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())

壮志饥餐胡虏肉,笑谈渴饮匈奴血。
易水萧萧西风冷,满座衣冠似雪。
俱往矣,数风流人物,还看今朝。
想当年,金戈铁马,气吞万里如虎。
天姥连天向天横,势拔五岳掩赤城。
乱石穿空,惊涛拍岸,卷起千堆雪。
我自横刀向天笑,去留肝胆两昆仑。
君不见黄河之水天上来,奔流到海不复回。
生当作人杰,死亦为鬼雄。至今思项羽,不肯过江东。
白日放歌须纵酒,青春作伴好还乡。
长风万里送秋雁,对此可以酣高楼。
长风破浪会有时,直挂云帆济沧海。
马作的卢飞快,弓如霹雳弦惊,了却君王天下事,赢得生前身后名。
此去泉台招旧部,旌旗十万斩阎罗。

- 可以将文件在计算机中的准确位置告诉Python,这称为绝对文件路径
- 在Linux和OSX中:’/home/ehmatthes/other_files/text_files/filename.txt’
- 在windows系统中:C:\Study\Python\Python\Python_work\pi_digits.txt
file_path = 'C:\Study\Python\Python\Python_work\pi_digits.txt'
with open(file_path) as file_object:
contents = file_object.read()
print(contents.rstrip())
逐行读取
- 检查文件中的每一行,或者以某种方式修改文件中的文本
- 对文件对象使用for循环
file_path = 'C:\Study\Python\Python\Python_work\pi_digits.txt'
with open(file_path) as file_object:
for line in file_object:
print(line)
运行:

- 出现空白行原因:
- 在文件中,每行的末尾都有一个看不见的换行符,print语句会加上一个换行符,因此每行末尾都有两个换行符,一个来自文件,另一个来自print语句,撤销多余的空白行,可在print语句中使用rstrip()
创建一个包含文件各行内容的列表
- 使用关键字with时,open()返回的文件对象只在with代码块内可用
- 要在with代码块外访问文件的内容,可在with代码块内将文件存储在一个列表中,并在with代码块外使用该列表
- 使用方法readlines()从文件中读取每一行,并将其存储在一个列表中
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line)
使用文件的内容
- 将文件读取到内存中后,就可以采用任何方式使用这些数据了
- 将其中的所有行都存储在一个列表中
- 创建变量用于存储圆周率的值
- 使用for循环,将每行都加入到变量中个,并删除末尾的换行符
- 方法:ristip()删除右边末尾的空格,strip()删除多余的空格
- 读取文本文件时, Python 将其中的所有文本都解读为字符串。如果你读取的是数字,并要将其作为数值使用,就必须使用函数 int() 将其转换为整数,或使用函数 float() 将其转换为浮点数。
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pr_string += line.rstrip()
print(pi_string)
print(len(pi_string))
3.1415926535
8979323846
2643383279
运行:

包含一百万位的大型文件
- 无需对程序做任何修改,只需将这个文件传递给程序即可
- 对于你可处理的数据量, Python 没有任何限制;只要系统的内存足够多,你想处理多少数据都可以。
- 访问列表使用切片[:]
filename = 'pi_million_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
print(pi_string[:52] + '.....')
print(len(pi_string))
运行:

圆周率值中包含你的生日吗
filename = 'pi_million_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
birthday = ""
while birthday != 'quit':
birthday = input("请输入您的生日:")
if birthday == 'quit':
break
elif birthday in pi_string:
print("你的生日在这个1000000圆周率值中!")
else:
print("你的生日不在圆周率值中!!!")
运行:

练习
filename = 'learning_python.txt'
print('--' * 80)
print("读取整个文件:")
with open(filename) as file_object:
lines = file_object.read()
print(lines)
print('--' * 80)
print("遍历文件对象:")
with open(filename) as file_object:
print("多余空白原因是:文本文件每行自带看不见的换行符,print函数也有换行功能,所有存在两个换行符")
for line in file_object:
print(line)
with open(filename) as file_object:
print("解决多余空白方法:rstrip()-->行末尾空白删除,strip()-->整行空白删除")
for line in file_object:
print(line.rstrip())
print('--' * 80)
print("存储在一个列表中:")
with open(filename) as file_object:
lines = file_object.readlines()
print(lines)
print('--' * 80)
print("遍历列表中的每一行:")
for line in lines:
print(line.rstrip())
print('--' * 80)
In Python you can store as much information as you want.
In Python you can connect pieces of information.
In Python you can model real-world situations.
In Python you can make a chat
运行:

message = "I really like dogs."
message.replace('dog', 'cat')
'I really like cats.'
'I really like cats.'
In Python you can store as much information as you want.
In Python you can connect pieces of information.
In Python you can model real-world situations.
In Python you can make a chat
filename = 'learning_python.txt'
print('--' * 80)
print("读取整个文件:")
with open(filename) as file_object:
lines = file_object.read()
print( lines.replace('Python','C'))
print('--' * 80)
print("遍历文件对象:")
with open(filename) as file_object:
print("多余空白原因是:文本文件每行自带看不见的换行符,print函数也有换行功能,所有存在两个换行符")
for line in file_object:
print(line.replace('Python', 'C'))
with open(filename) as file_object:
print("解决多余空白方法:rstrip()-->行末尾空白删除,strip()-->整行空白删除")
for line in file_object:
print(line.replace('Python', 'C').rstrip())
print('--' * 80)
print("存储在一个列表中,遍历列表中每一行:")
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.replace('Python', 'C').rstrip())
print('--' * 80)
运行:
