for
循环是一种控制结构,用于重复执行一段代码,直到满足特定条件。在读取不同文件名的场景中,for
循环可以遍历文件名列表,并对每个文件执行相应的操作。
for
循环提供了一种简洁的方式来遍历集合中的元素。假设我们有一个包含文件名的列表 file_list
,我们希望读取每个文件的内容并打印出来。
file_list = ['file1.txt', 'file2.txt', 'file3.txt']
for filename in file_list:
try:
with open(filename, 'r') as file:
content = file.read()
print(f"Content of {filename}:")
print(content)
except FileNotFoundError:
print(f"File {filename} not found.")
except Exception as e:
print(f"An error occurred while reading {filename}: {e}")
try-except
块捕获 FileNotFoundError
异常,并进行相应的处理。open(filename, 'r', encoding='utf-8')
。通过以上方法,可以有效地使用 for
循环读取不同的文件名,并处理可能遇到的问题。
领取专属 10元无门槛券
手把手带您无忧上云