如何在python程序中读取其他文件?这里主要用到了agrv用以接收列表变量、open方法用以打开文件、read方法读取文件、close方法关闭文件。读取文件的过程逻辑很简单,具体见如下代码:(要打开的文件为“ex15_sample.txt”)
from sys import argv
script, filename = argv
txt = open(filename)#【打开文件】
#这行代码描述了打开文件的过程。open先接受一个参数,然后返回一个值。这里将这个值赋给了变量txt。txt就相当于我们要读取的文件。
print("Here's your file %r:" %filename)
print(txt.read())#【读取文件】
#这里的txt变量即为从open获得的东西(一个文件),可以用【句点加命令】的方式来操作文件,如".read()"
print("现在关闭文件")
print(txt.close())#【关闭文件】
print("Type the filename again:")
file_again = input("> ")
txt_again = open(file_again)
print(txt_again.read())#再次打开文件
print("现在关闭文件")
print(txt_again.close())#再次关闭文件
保存文件,在命令行中输入命令:python ex15.py ex15_sample.txt 和 ex15_sample.txt 以执行程序。结果如图:
总结:文件的读取大致分为三步:
1.打开文件(使用open方法)
2.读取文件(使用read方法)
3.关闭文件(使用close方法)
以上三步应对应上面的代码进行记忆,要勤加练习。