pi_digits.txt3.141592653589793238462643383279
# file_reader.py
# 打开文件,函数open()接受一个参数:要打开的文件的名称。Python在当前执行的文件所在的目录中查找指定的文件。函数open()返回一个表示文件的对象
# 关键字with在不再需要访问文件后将其关闭,Python会在合适的时候自动将其关闭
with open('pi_digits.txt') as file_object:# 使用方法read()读取这个文件的全部内容contents = file_object.read()# 相比于原始文件,该输出将在末尾多一个空行,因为read()到达文件末尾时返回一个空字符串,而将这个空字符串显示出来就是一个空行。要删除多余的空行,可使用rstrip()。
print(contents.rstrip())
要让Python打开不与程序文件位于同一个目录中的文件,需要提供文件路径,让Python到系统的指定位置去查找。
# (1)相对文件路径
# 显示文件路径时,Windows系统使用反斜杠而不是斜杠,但在代码中依然可以使用斜杠
with open('text_files/filename.txt') as file_object:
# (2)绝对文件路径
file_path = '/home/ehmattes/other_files/filename.txt'
with open(file_path) as file_object
# file_reader.py
filename = 'pi_digits.txt'
with open(filename) as file_object:for line in file_object:# 在这个文件中,每行的末尾都有一个看不见的换行符print(line)
使用关键字with时,open()返回的文件对象只在with代码块内可用。如果要在with代码块外访问文件的内容,可在with代码块内将文件的各行存储在一个列表中,并在with代码块外使用该列表。
filename = 'pi_digits.txt'
with open(filename) as file_object:# readlines()从文件中读取每一行,并将其存储在一个列表中lines = file_object.readlines()for line in lines:print(line.rstrip())
# pi_string.py
filename = 'pi_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)
print(f"{pi_string[:20]}...") # 输出前20位
print(len(pi_string))
读取文本文件时,Python将其中的所有文本都解读为字符串。
# pi_string.py
filename = 'pi_digits.txt'
with open(filename) as file_object:lines = file_object.readlines()pi_string = ''
for line in lines:pi_string += line.strip()birthday = input("Enter your birthday, in the form mmddyy: ")
if birthday in pi_string:print("Your birthday appears in the first million digits of pi!")
else:print("Your birthday does not appear in the first million digits of pi.")
动手试一试
# write_message.py
filename = 'pi_digits.txt'
# 调用open()提供了两个实参,第一个实参也是要打开的文件的名称。第二个实参告诉Python以何种模式打开文件(读取模式:'r',写入模式:'w',读写模式:'r+',附加模式:'a')。如果省略了模式实参,Python将以默认的只读模式打开文件
# 如果要写入的文件不存在,函数open()将自动创建它。
# 以写入模式打开文件时,若指定的文件已经存在,Python将在返回文件对象前清空该文件的内容
with open(filename, 'w') as file_object:# 使用文件对象的方法write()将一个字符串写入文件# Python只能将字符串写入文本文件。要将数值数据存储到文本文件中,必须先使用函数str()将其转换为字符串格式file_object.write("I love programming.")
函数write()不会在写入的文本末尾添加换行符。
# write_message.py
filename = 'pi_digits.txt'
with open(filename, 'w') as file_object:file_object.write("I love programming.\n")file_object.write("I love creating new games.\n")
以附加模式打开文件时,Python不会在返回文件对象前清空文件的内容,而是将写入文件的行添加到文件末尾。如果指定的文件不存在,Python将为你创建一个空文件。
# write_message.py
filename = 'pi_digits.txt'
with open(filename, 'a') as file_object:file_object.write("I also love finding meaning in large datasets.\n")file_object.write("I love creating apps that can run in a browser.\n")
动手试一试