import os
def get_fname():
while True:
fname = input('filename: ')
if not os.path.exists(fname): #os.path.exists(),查看文件是否存在
break
print('%s already exists. Try again' % fname)
return fname
def get_content():
content = []
print('输入数据,输入end结束')
while True:
line = input('>') #输入的提示符号,见测试
if line == 'end':
break
content.append(line) #向content列表中加入内容
return content
def wfile(fname,content):
with open(fname,'w') as fobj:
fobj.writelines(content) #把content列表中的数据写入文件中
if __name__ == '__main__':
fname = get_fname()
content = get_content()
content = ['%s\n' % line for line in content]
wfile(fname,content)
# 测试
# [root@room9pc01 KINGSTON]# python3 43生成文本文件.py
# filename: /tmp/abc.txt
# 输入数据,输入end结束
# >abc
# >dvd
# >haha
# >end
# [root@room9pc01 KINGSTON]# cat /tmp/abc.txt
# abc
# dvd
# haha