以下3步问正确的程序片段:
#! /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
#! /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()
#! /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)
一下为笔者自己所写:
#! /usr/bin/Python2.7
‘makeTextFile2--create text file‘
import os
def write_file():
ls = os.linesep
fileName = raw_input(‘plz input filename:‘)
while True:
if os.path.exists(fileName)
print(‘file already exists!‘)
else:
fileName = raw_input(‘plz input filename[A3] :‘)
#get content in line
all = []
print(‘\nEnter line(‘.‘ to quit).\n‘)
while True:
else:
fobj = open(fileName, ‘w[A8] ‘)
fileName.writelines(‘%s%s‘ %(x, ls) for x in all[A9] )
#! /usr/bin/Python2.7
‘readTextFile2--read text file‘
import os
try:
fobj = open(fileName, ‘r‘)
except IOError as err:
print (‘read file error:{0}‘.format(err))
else:
for eachLine in fobj:
print(eachLine)
fobj.close()
#! /usr/bin/Python2.7
‘main2—main function’
import readTextFile.py
fileName = makeTextFile.write_file()
readTextFile.read_file(fileName)[A1]注释写明白,是fileName
[A2]判断完成之后应该立即提示输入fileName
[A3]如果之前没有此file则创建,直接break
[A4]改为raw_input
[A6]完全瞎写
[A7]应该是将新的entry添加到all数组中
[A8]缺少try except语句
[A9]这里是数组
[A10]最后最好有个提示输入完成,略显程序完善
[A11]因为下面要调用write_file,所以在函数最后要有一个return值
[A12]因为需要使用别处传来的参数,所以定义是需要参数fileName
[A13]引用是不需要加后缀
原文地址:http://blog.csdn.net/woody891/article/details/28426057