Python函数示例:如何从文件中读取文本
发布时间:2023-07-02 08:26:36
以下是一个简单的Python函数示例,用于从文件中读取文本并返回前1000个字符:
def read_text_from_file(file_path):
try:
with open(file_path, 'r') as file:
text = file.read()
return text[:1000]
except FileNotFoundError:
print("File not found.")
except IOError:
print("Error reading file.")
使用示例:
file_path = "example.txt" # 替换为实际文件路径 text = read_text_from_file(file_path) print(text)
请确保将file_path替换为实际的文件路径。函数会尝试打开该文件并读取其中的文本,然后返回前1000个字符。如果文件找不到或无法读取,将抛出相应的异常并打印错误信息。
