import os
# # 检查文件是否存在,文件位于脚本所在的文件夹平级的文件夹“UIS"内,文件名为1.txt
file_path = '../UIS/1.txt'
if not os.path.isfile(file_path): # 文件不存在,创建文件
with open(file_path, 'w') as file: # 写方式打开文件
file.write('') # 创建一个空文件或可以添加一些初始文本
print("文件已创建。")
else:
print(f"文件 {file_path} 已存在,正在打开...")
# 文件已存在,打开文件
with open(file_path, 'r') as file:
# 读取文件内容
content = file.read()
print("文件内容:")
print(content)
检查文件是否存在,如不存在就创建
于 2024-05-13 23:21:01 首次发布