资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

python文件操作(创建与读取)

###############################创建文件###########################################
#!/usr/bin/env python

'''make a test file'''

import os 

ls = os.linesep

#get file name

fname = raw_input('Enter Filename: ')

while True:
    if os.path.exists(fname):
        print('ERROR: %s already exists' % fname )
        exit()
        break
    else:
        break

#get file content(test) lines
all = []
print("Enter lines ('.' by itself to quit)")

#loop until user terminates input
while True:
    entry = raw_input('> ')
    if entry == '.':
        break
    else:
        all.append(entry)

#write lines to file with proper line-ending
with open(fname,'w') as f:
    f.writelines(['%s%s' %(x,ls) for x in all])

print 'DONE!'

###################################读取文件######################################
#!/usr/bin/env python

'''read and display text file'''

#get file name
fname = raw_input("Enter filename: ")
print

#attempt to open file for reading
try:
    fobj = open(fname,'r')
except IOError,e:
    print('***file open error:',e)
else:
    #display content to the screen
    for eachLine in fobj:
        print eachLine
    fobj.close()

网站栏目:python文件操作(创建与读取)
文章网址:http://cdkjz.cn/article/ipcgoi.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220