苏泽湛 发表于 2017-4-25 09:55:18

自学python练习题

1.输入一个文件名,检测是否存在,如果不存在创建文件并写入内容:

import os
while True:
filename=input('Please enter the filename')
if os.path.exists(filename):
print('the file is exist')
break
else:
all=[]
while True:
content=input('>')
if content=='.':
print('Exit')
break
else:
all.append(content)
fobj=open(filename,'w')
str_list=
fobj.writelines(str_list)
fobj.close()
break

2.读入文件并打印出来,如果不存在则提示错误信息

def readFile():
filename=input('Please enter the file name')
print(filename)
try:
fobj=open(filename,'r')
except IOError as e:
print('%s is open error'%filename)
else:
for eachLine in fobj:
print(eachLine)
fobj.close()
页: [1]
查看完整版本: 自学python练习题