Python函数:如何从文件中读取并打印内容
发布时间:2023-07-06 12:04:08
在Python中,可以使用open()函数来打开一个文件,并使用read()方法来读取文件的内容。下面是一个将文件内容读取并打印的示例:
def read_and_print_file(filename):
try:
# 使用open()函数以只读模式打开文件
file = open(filename, 'r')
# 使用read()方法读取文件的全部内容
content = file.read()
# 打印文件内容
print(content)
# 关闭文件
file.close()
except FileNotFoundError:
print("文件不存在")
except:
print("无法打开文件")
# 调用函数,传入要打开的文件名
read_and_print_file("example.txt")
