要使用Python的open函数来读取文件,你需要使用以下步骤:
file = open("example.txt", "r")
content = file.read()
也可以使用文件对象的readline方法逐行读取文件内容:
line = file.readline() # 读取一行内容
file.close()
完整的读取文件的代码示例:
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
注意:为了确保文件能够正确关闭,可以使用with语句来打开文件。with语句会在代码块结束后自动关闭文件,无需手动调用close方法。例如:
with open("example.txt", "r") as file:
content = file.read()
print(content)
这样可以避免忘记关闭文件而导致资源泄漏的问题。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:如何使用python读取文件