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))
完!


浙公網安備 33010602011771號