首页 > 代码库 > Python读写文本文档详解
Python读写文本文档详解
以下3步问正确的程序片段:
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)
一下为笔者自己所写:
1.写文档
#! /usr/bin/Python2.7
‘makeTextFile2--create text file‘
import os
def write_file():
ls = os.linesep
#get file[A1]
fileName = raw_input(‘plz input filename:‘)
while True:
if os.path.exists(fileName)
print(‘file already exists!‘)
[A2]
else:
fileName = raw_input(‘plz input filename[A3] :‘)
#get content in line
all = []
print(‘\nEnter line(‘.‘ to quit).\n‘)
while True:
entry = input[A4] (‘>‘)
[A5]
else:
break[A6]
entry.append(all[A7] )
fobj = open(fileName, ‘w[A8] ‘)
fileName.writelines(‘%s%s‘ %(x, ls) for x in all[A9] )
fobj.close[A10] [A11] ()
2.读文档
#! /usr/bin/Python2.7
‘readTextFile2--read text file‘
import os
def read_file[A12] ():
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()
3.主函数
#! /usr/bin/Python2.7
‘main2—main function’
import makeTextFile.py[A13]
import readTextFile.py
[A14]
fileName = makeTextFile.write_file()
readTextFile.read_file(fileName)[A1]注释写明白,是fileName
[A2]判断完成之后应该立即提示输入fileName
[A3]如果之前没有此file则创建,直接break
[A4]改为raw_input
[A5]If entry==’.’
Break
明显缺少语句
[A6]完全瞎写
[A7]应该是将新的entry添加到all数组中
[A8]缺少try except语句
[A9]这里是数组
[A10]最后最好有个提示输入完成,略显程序完善
[A11]因为下面要调用write_file,所以在函数最后要有一个return值
[A12]因为需要使用别处传来的参数,所以定义是需要参数fileName
[A13]引用是不需要加后缀
[A14]需要主函数
知识详解及延伸:
问题1.os.linesep
os.linesep字符串给出当前平台使用的行终止符。例如,Windows使用‘\r\n‘,Linux使用‘\n‘而Mac使用‘\r‘。
例: fileappend=open(‘/home/zll/new.txt‘,‘a‘)
fileappend.write(‘zhui jia content‘)
fileappend.write(‘\n‘) //不用\n 如果使用os.linesep
while True:
aline=raw_input("Enter a line(‘.‘ to quit):")
if aline != ".":
fileappend.write(‘%s%s‘ % (aline,os.linesep))
else:
break
fileappend.close()
问题2.
fileName.writelines(‘%s%s‘ %(x, ls) for x in all)这里应该用数组。
问题3.
如果本函数在其他函数中调用,需要用的返回值的话,记得最后return。
问题4.
Import时不需要写文件后缀的
问题5.
主函数需要if __name__==’__main__’:的!!!