1 案例1:创建文件
1.1 问题
编写mktxtfile.py脚本,实现以下目标:
编写一个程序,要求用户输入文件名
如果文件已存在,要求用户重新输入
提示用户输入数据,每行数据先写到列表中
将列表数据写入到用户输入的文件名中
1.2 方案
用三个函数分别实现文件名获取、文件内容获取、将获取到的文件内容写入get_fname()函数获取的文件中 这三个方法,最终调用三个函数,完成文件创建:
1.获取文件名函数get_fname():利用while语句循环判断文件名是否存在,input文件名,如果不存在,循环停止,返回用户输入的文件名,如果存在,提示已存在,重新进入循环,直至文件名不存在为止,返回文件名用户输入的文件名
2.文件内容获取函数get_contents():创建空列表存储获取到的数据,利用while语句让用户循环输入数据,如果输入的数据是end,循环停止,返回列表中内容,如果输入的数据不是end,将输入的数据追加到列表结尾,返回列表中内容
3.wfile()函数:用with语句将获取到的文件以写方式打开,这样打开代码块结束后文件会自动关闭,将get_contents()函数返回内容写入到已打开文件中
4.最终当用户cat文件名时,可以看到写入结果
1.3 步骤
实现此案例需要按照如下步骤进行。
步骤一:编写脚本
[root@localhost day04]# vim mktxtfile.py
#!/usr/bin/env python3
import os
def get_fname():
while True:
filename = input('请输入文件名:')
if not os.path.exists(filename):
break
print('%s 已存在,请重试。' % filename)
return filename
def get_contents():
contents = []
print('请输入内容,结束请输入end。')
while True:
line = input('> ')
if line == 'end':
break
contents.append(line)
return contents
def wfile(fname, contents):
with open(fname, 'w') as fobj:
fobj.writelines(contents)
if __name__ == '__main__':
fname = get_fname()
contents = get_contents()
contents = ['%s\n' % line for line in contents]
wfile(fname, contents)
步骤二:测试脚本执行
[root@localhost day04]# ls
adduser.py format_str2.py list_method.py mylist.py string_op.py
checkid.py format_str.py mkseq.py randpass2.py
fmtoutput.py get_val.py mktxtfile.py seq_func.py
[root@localhost day04]# python3 mktxtfile.py
请输入文件名:passwd
请输入内容,结束请输入end。
> nihao,welcom
> woshi
> end
[root@localhost day04]# python3 mktxtfile.py
请输入文件名:mkseq.py
mkseq.py 已存在,请重试。
请输入文件名:randpass.py
请输入内容,结束请输入end。
> myname
> end
[root@localhost day04]# cat passwd
nihao,welcom
woshi
[root@localhost day04]# cat randpass.py
myname
[root@localhost day04]# ls
adduser.py format_str2.py list_method.py mylist.py randpass.py
checkid.py format_str.py mkseq.py passwd seq_func.py
fmtoutput.py get_val.py mktxtfile.py randpass2.py string_op.py