python写文件、读取文件、按行修改文件
2012-11-29 16:24
585 查看
#!/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()
相关文章推荐
- python按行读取文件,如何去掉换行符"\n"
- Python按行读取大文件
- Python按行读取文件的实现方法【小文件和大文件读取】
- Python按行读取大文件
- python 按行读取并判断按行写入文件
- python按行读取文件,如何去掉换行符"\n"
- ZH奶酪:Python按行读取文件
- python读写文件数据(换行写入以及按行读取)
- Python按行读取大文件
- Python按行读取大文件
- python中的按行读取文件
- python按行读取文件 去掉换行符"\n"
- 文件的创建,读取,写入,修改,删除---python入门
- Python按行读取大文件
- Python按行读取大文件
- Python 按行读取文件内容
- python按行读取文件,去掉每行的换行符"\n"
- python 读写文件,按行修改文件的方法
- python3将csv文件中的两列数据读取出来,并且按行写入txt文本之中
- python按行读取文件 如何去掉换行符 "\n"