python类库31[读写文件]
一 Open 函数
open(path [,mode [,buffersize]])
1)path文件的路径。
2)mode文件的读写模式。
r读打开存在的文件,
w写打开文件,如果文件存在以前的内容被覆盖,如果文件不存在则创建之,
a打开存在的文件添加新内容,
r+读写打开文件,以前的被人被保留,
w+读写打开文件,以前的内容被覆盖,
a+读写打开文件,以前的被人被保留,
b与rwa之一配合使用,表示以二进制打开,
u与rwa之一配合使用,Applies the "universal" newline translator to the file as it is opened.
3)buffersize指定访问文件时的buffer模式。
0表示不使用buffer,
1表示行buffer,
其他的正整数表示buffer的大小,
当忽略或为负数时使用默认的buffersize。
二 实例
outPath = "text.txt"
inPath = outPath
print('---------------------------------')
#Open a file for writing
file = open(outPath, 'w')
if file:
file.write('hello\ntom\n')
file.writelines('bye!')
file.close()
else:
print ("Error Opening File.")
print('---------------------------------')
#Open a file for reading
file = open(inPath, 'r')
if file:
print(file.read())
#print(file.readlines())
file.close()
else:
print ("Error Opening File.")
print('---------------------------------')
# read line from file
import linecache
filePath = "text.txt"
print (linecache.getline(filePath, 1))
print (linecache.getline(filePath, 3))
linecache.clearcache()
print('---------------------------------')
# read word from file
filePath = "input.txt"
wordList = []
wordCount = 0
#Read lines into a list
file = open(filePath, 'rU')
for line in file:
for word in line.split():
wordList.append(word)
wordCount += 1
print (wordList)
print ("Total words = %d" % wordCount)
print('---------------------------------')
# count line of file
filePath = "input.txt"
lineCount = len(open(filePath, 'rU').readlines())
print ("File %s has %d lines." % (filePath,lineCount))
inPath = outPath
print('---------------------------------')
#Open a file for writing
file = open(outPath, 'w')
if file:
file.write('hello\ntom\n')
file.writelines('bye!')
file.close()
else:
print ("Error Opening File.")
print('---------------------------------')
#Open a file for reading
file = open(inPath, 'r')
if file:
print(file.read())
#print(file.readlines())
file.close()
else:
print ("Error Opening File.")
print('---------------------------------')
# read line from file
import linecache
filePath = "text.txt"
print (linecache.getline(filePath, 1))
print (linecache.getline(filePath, 3))
linecache.clearcache()
print('---------------------------------')
# read word from file
filePath = "input.txt"
wordList = []
wordCount = 0
#Read lines into a list
file = open(filePath, 'rU')
for line in file:
for word in line.split():
wordList.append(word)
wordCount += 1
print (wordList)
print ("Total words = %d" % wordCount)
print('---------------------------------')
# count line of file
filePath = "input.txt"
lineCount = len(open(filePath, 'rU').readlines())
print ("File %s has %d lines." % (filePath,lineCount))
完!