编写程序,在指定文件路径读方式
file_name=input("请输入要打开的文件名:")
if file_name == 'test.txt':
with open('test.txt') as fp:
print(fp.read())
else:
with open('022') as fp:
print(fp.read())
```打开指定文件名,要求如果文件不存在提示异常错误并且创建新的同名文件。
编写程序,在指定文件路径读方式
file_name=input("请输入要打开的文件名:")
if file_name == 'test.txt':
with open('test.txt') as fp:
print(fp.read())
else:
with open('022') as fp:
print(fp.read())
```打开指定文件名,要求如果文件不存在提示异常错误并且创建新的同名文件。
try:
with open('abc.txt','r') as f:
pass
except Exception as e:
print(e)
with open('abc.txt','w') as f:
pass
或者使用系统内置的os模块判断文件是否存在
import os
file_name = input('请输入要打开的文件名:')
if os.path.isfile(file_name):
with open(file_name,'r') as f:
pass
else:
print('文件不存在,创建新文件')
with open(file_name,'w') as f:
pass