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

发布时间:2020-07-03 20:05:58 作者:大陌
来源:网络 阅读:371
###############################创建文件###########################################
#!/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()


推荐阅读:
  1. Python 关于文件操作
  2. python文件操作

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python 文件操作 python文件操作

上一篇:Toast源码深度分析

下一篇:Oracle Study---Oracle 11g 不可见索引案例

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》