用python实现新建一个文件并输入内容

#/usr/bin/env python

#模块文档
"in order to create a file "

#引入模块
import os
#给出当前平台的行终止符
ls = os.linesep

#判断文件是否存在+
while True:
        fname = input("please input the name of the file:")
        if os.path.exists(fname):
            print ("Error:'%s' already exists" % fname)
            continue
        else:
            break

#创建一个新文件
all = []
#提示语:当输入.时即结束输入
print ("Enter line ('.' by itself to quit).\n")

#loop  until user terminate input
while True:
    entry = input(">")
    if entry == ".":
        break
    else:
        all.append(entry)


#将输入写入文件中
#以可写的方式打开创建的文件
fobj = open(fname,'w')
for x in all:
    #wirtelinees()方法的作用是将可迭代对象(这里是个列表)写入文件中,如下的作用:一次循环输入列表中的一个对象和一个当前的行终止符
    fobj.writelines(['%s%s' % (x,ls)])
fobj.close()
print ('DONE!')
判断一个文件是否存在,若存在则按行输出文件内容到屏幕上
#/usr/bin/env python

"open a file"

#get a file name
fname = input("Enter filename:")

#attempt to open file for reading

try:
    fobj = open(fname,'r')
except:
    print ("'%s' open error or the file does not exit" % fname)
else:
    #display content to the screen
    for eachLine in fobj:
        print (eachLine)
    fobj.close()

猜你喜欢

转载自blog.csdn.net/myydebk666/article/details/82459817