(1) 从文件中读取数据
首先编写 pi.txt
3.1415926535
8979323846
2643383279
然后编写 file_reader.py
# 当前运行的是file_reader.py,因此Python在file_reader.py所在的目录中查找pi.txt。
# 关键字with在不再需要访问文件后将其关闭。
with open('pi.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
输出吧,皮卡丘~
PS D:\vscode> & C:/Users/Administrator/AppData/Local/Programs/Python/Python37/python.exe d:/vscode/file_reader.py
3.1415926535
8979323846
2643383279
PS D:\vscode>
(2) 文件路径
例如,程序存储在python_work文件夹中,而python_work中,有text_files文件夹。