Python:读文件和写文件
Python:读文件和写文件
1. 写文件
- #! /usr/bin/python3
- 'makeTextFile.py -- create text file'
- import os
- def write_file():
- "used to write a text file."
- ls = os.linesep
- #get filename
- fname = input("Please input filename:")
- while True:
- if os.path.exists(fname):
- print("Error: '%s' already exists" % fname)
- fname = input("Please input filename:")
- else:
- break
- #get file conent linesOnScreen
- all = []
- print("\nEnter lines ('.' to quit).\n")
- while True:
- entry = input('>')
- if entry == '.':
- break
- else:
- all.append(entry)
- try:
- fobj = open(fname, 'w')
- except IOError as err:
- print('file open error: {0}'.format(err))
- fobj.writelines(['%s%s' % (x, ls) for x in all])
- fobj.close()
- print('WRITE FILE DONE!')
- return fname
2. 读文件
- #! /usr/bin/python3
- 'readTextFile.py -- read and display text file.'
- def read_file(filename):
- 'used to read a text file.'
- try:
- fobj = open(filename, 'r')
- except IOError as err:
- print('file open error: {0}'.format(err))
- else:
- for eachLine in fobj:
- print(eachLine)
- fobj.close()
3. 主程序
- #! /usr/bin/python3
- 'write_and_read_file.py -- write and read text file.'
- import makeTextFile
- import readTextFile
- if __name__ == '__main__':
- #wrie file
- filename = makeTextFile.write_file()
- #read file
- readTextFile.read_file(filename)
4.运行结果
- Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on winxp-duanyx, Standard
- >>> Please input filename:d:\testpython.log
- Enter lines ('.' to quit).
- >this is a test file.
- >ok ,let us input . to end the content input.
- >.
- WRITE FILE DONE!
- this is a test file.
- ok ,let us input . to end the content input.
- >>>
相关推荐
IT之家 2020-03-11
graseed 2020-10-28
zbkyumlei 2020-10-12
SXIAOYI 2020-09-16
jinhao 2020-09-07
impress 2020-08-26
liuqipao 2020-07-07
淡风wisdon大大 2020-06-06
yoohsummer 2020-06-01
chenjia00 2020-05-29
baike 2020-05-19
扭来不叫牛奶 2020-05-08
hxmilyy 2020-05-11
黎豆子 2020-05-07
xiongweiwei00 2020-04-29
Cypress 2020-04-25
冰蝶 2020-04-20