案例:创建文件
(1)编写一个程序文件,要求用户名输入文件名
(2)如果文件已存在,要求用户重新输入
(3)提示用户输入数据,每行数据先写到列表中
(4)将列表数据写入到用户输入的文件名中
1.发呆。思考程序的运作方式。交互?非交互?如果是交互的,程序有什么输出,要求用户有什么输入。
# python mkfile.py
filename: /etc/hosts
文件已存在,请重试
filename: /etc
文件已存在,请重试
filename: /tmp/myfile.txt
请输入内容,在单独的一行上输入end结束
(end to quit)> hello world!
(end to quit)> ni hao!
(end to quit)> how are you?
(end to quit)> end
# cat /tmp/myfile.txt
hello world!
ni hao!
how are you?
2. 思考程序有哪些功能,将功能编写成函数,这样将大的、复杂的问题简为一个个的小的问题
def get_fname():
'返回文件名'
def get_content():
'返回内容'
def wfile(fname, content):
'将内容content写入文件fname
3.书写主程序代码,按顺序调用函数
def get_fname():
'返回文件名'
def get_content():
'返回内容'
def wfile(fname, content):
'将内容content写入文件fname'
if __name__ == '__main__':
fname = get_fname()
content = get_content()
wfile(fname, content)
4.填写每个具体的函数主体代码
import os
def get_fname():
'返回文件名'
while 1:
fname = get_fname('filename:')
if not os.path.exists(fname):
break
print('文件已存在,请重试!')
return fname
def get_content():
'返回内容'
content = []
print('请输入内容,在单独的一行上输入end结束')
while 1:
line = input('end to quit:')
if line == 'end':
break
content.append(line)
return get_content()
def wfile(fname, content):
'将内容content写入文件fname'
with open(fname, 'w') as fobj:
fobj.writelines(content)
if __name__ == '__main__':
fname = get_fname()
content = get_content()
content = ['%s\n' % line for line in content]
wfile(fname, content)