任务要求:判断当前路径中是否有oldfilename.txt文件,如果存在则按行输出内容,否则创建该文件。
任务拆解:
1.文件存在则输出;
2.文件不存在则创建。
代码:
import os
def read_or_create_file(filename):
# 检查文件是否存在
if os.path.isfile(filename):
# 如果文件存在,则按行输出文件内容
with open(filename, 'r') as file:
for line in file:
print(line.strip()) # 去除每行末尾的换行符并输出
else:
# 如果文件不存在,则创建文件并写入示例内容
with open(filename, 'w') as file:
file.write("This is a new file.\n")
file.write("It has been created because the file '{}' did not exist.".format(filename))
print("文件 '{}' 已创建并写入内容。".format(filename))
filename = 'oldfilename.txt'
read_or_create_file(filename)
模块与函数:
os.path.isfile(destination)
1.destination:目标路径;
2.功能:判断该路径是否为文件。