先上代码
from sys import argv
script , filename = argv # filename 这个名字的文件夹需要提前存在,与py文件在同一目录下
txt = open(filename)
print("Here's your file %r:" %filename)
print(txt.read()) # 读取txt中存在的内容
txt.close() # 清空资源
print("Type the filename again:") # 需要txt文件和此文件在同一目录
file_again = input(">")
txt_again = open(file_again)
print(txt_again.read())
txt_again.close() # 清空资源,将内容从内存中存储到硬盘中
ex15的内容是:
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
本次练习目的:读取已存在的文件
前提:python文件和txt文件存在于同一目录,否则如图
注意点1:在使用open函数时,必须对其进行赋值,否则打开是没有意义的。后续的read函数就会找不到可读对象
注意点2:open和close是成双成对出现的,若只有open没有close,则所有内容在内存上,没有被真正写入,一旦关闭程序,内容会被清除。