python写文件、读取文件、按行修改文件

#!/usr/bin/env python 
# -*- coding: utf-8 -*-
'''
Created on 2012-11-29
@author: Eliot
make and read a file
'''
import os
ls = os.linesep;

def makefile():
    #input the file name
    while True:
        aFileName = raw_input('Enter a file Name:')
        if os.path.exists(aFileName):
            print '%s already exists!' % (aFileName)
        else:
            break
    #input the file text
    text = []
    print "\nEnter lines ('.' by itself to quit).\n"
    while True:
        entry = raw_input('>')
        if entry == '.':
            break
        else:
            text.append(entry)
    #input the file
    file = open(aFileName, 'w')
    file.writelines(['%s%s' % (x, ls) for x in text])
    file.close()
    print 'Make file over!'
def readfile():
    #input the file name
    while True:
        fileName = raw_input('Enter a file Name to read:')
        if os.path.exists(fileName):
            break
        else:
            print 'The file is not exists!'
    #read the file
    file = open(fileName, 'r')
    for x in file:
        print x,
    file.close()
    print 'Read file over!'

def Modify():
    #input the file name
    while True:
        mFileName = raw_input('Enter a file name:')
        if os.path.exists(mFileName):
            break
        else:
            print 'The file is not exists!'
    #modify the file
    fileRead = open(mFileName, 'r')
    lines = fileRead.readlines()
    fileRead.close()
    
    fileWrite = open(mFileName, 'w')
    for line in lines:
        '''
        if line.strip().startswith('XYW'):
            insert = raw_input('Enter text:') + ls
            fileWrite.write(insert)
        else:
            fileWrite.write(line)
        '''
        print '%s' % line        
        insert = raw_input('>:') + ls
        fileWrite.write(insert)
    fileWrite.close()
def main():
    while True:
        print '1.make file 2.read file 3.modify file 4.exit'
        ch = int(raw_input(':'))
        if ch == 1:
            makefile()
        elif ch == 2:
            readfile()
        elif ch == 3:
            Modify()
        else:
            break
    print 'The game is over!'
if __name__ == '__main__':
    main()
    
    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值