四大名著
获取文件夹中所有txt文档的路径,使用 with...as 语句配合 open() 函数的以 r 的方式打开文档;使用 read() 函数读取文档。
文件名称已经存储在列表bookList,你还需要使用字符串拼接:
path + "/"+ 文件名称 + ".txt"
文件夹路径:
/Users/books
答案:
bookList=["三国演义","西游记","水浒传","红楼梦"]
路径
path="/Users/books"
for循环遍历列表bookList,将元素赋值给变量name
for name in bookList:
#将字符串拼接,赋值给变量filePath
filePath= path +"/" +name +".txt"
#使用with...as以rb方式,打开路径为filepath的图片,并赋值给bookFile
with open(filePath,"r") as bookFile:
#使用read()读取txtFile并赋值给data
data = bookFile.read()
#使用print()输出变量data
print(data)
注释:with open()的打开方式在for里面也是需要缩进的。
其次,要清楚这种题目的逻辑关系:首先是把路径什么的都找齐,然后先打开再读取。