python创建文件


这个脚本提示用户输入一个(尚不存在的)文件,然后由用户输入该文本的每一行,最后,将所有文本写入文本文件。

import os
ls=os.linesep

while True:
    fname=raw_input("Enter the the file name:")
    if os.path.exists(fname):
        print "Error,the file exists"
    else:
        break

all=[]
print "\nEnter liines('.'by itself to quit).\n"

while True:
    entry=raw_input('> ')
    if entry=='.':
        break
    else:
        all.append(entry)
fobj=open(fname,'w')
#fobj.writelines(['%s%s'%(x,ls) for x in all])
fobj.writelines((['%s'%x for x in all]))

fobj.close()
print 'Done!'
运行结果如下:
C:\Anaconda2\python.exe C:/Users/Auser.MEY/PycharmProjects/test1/test.py
Enter the the file name:C:\\Users\\Auser.MEY\\Desktop\\gooog.txt

Enter liines('.'by itself to quit).

> hello success
> .
Done!

Process finished with exit code 0

C:\\Users\\Auser.MEY\\Desktop路径下创建了一个名为gooog的txt文档,同时写入了hello success的内容
<img src="https://img-blog.csdn.net/20160726154711189?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />

如果输入多行数据,我们的目标是在文本文件中显示多行,因此需要插入行终止符,源程序部分需要进行修改。

fobj.writelines(['%s%s'%(x,ls) for x in all])

C:\Anaconda2\python.exe C:/Users/Auser.MEY/PycharmProjects/test1/test.py
Enter the the file name:C:\\Users\\Auser.MEY\\Desktop\\Test.txt

Enter liines('.'by itself to quit).

> hello python
> I love you.
> Thanks a lot
> .
Done!

Process finished with exit code 0

结果如下:


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值