def read_file(file_path):
try:
with open(file_path, 'r') as f:
file_content = f.read()
lines = file_content.split('\n')
words = file_content.split()
return (file_content, lines, words) # 返回元组
except FileNotFoundError:
print('文件不存在')
# 测试
file_path = 'test.txt'
result = read_file(file_path)
print(result)
说明:
read_file
函数接受一个文件路径参数;open
函数打开文件,读取文件内容;lines
和 words
列表;输出结果:
('This is a test file.\nIt is used for testing read_file function.\n',
['This is a test file.', 'It is used for testing read_file function.', ''],
['This', 'is', 'a', 'test', 'file.', 'It', 'is', 'used', 'for', 'testing', 'read_file', 'function.'])