读取没有文本扩展名的文本文件".txt"



我正在尝试读取Python 3.8中扩展名为".input"的文件。但是,它旨在作为文本文件读取。我尝试使用以下代码连接到该文件:

file = open('file.input', 'r')
print("The contents of the file are:",file)

但是,它不会输出"file.input"的内容(我在那里写了"Hello World"作为示例消息(。

您需要对open返回的对象调用read(或其他读取方法之一(。

with open('file.input', 'r') as f:
print(f.read())

with关键字有助于确保您打开的文件被关闭。有关python中文件I/O的更多信息,您应该阅读此处的文档:https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files。

最新更新