讀文字檔
input = open('data', 'r')
#第二個參數預設為r
input = open('data')
讀二進位檔案
input = open('data', 'rb')
讀固定位元組
file_object = open('abinfile', 'rb')
3.寫檔案
寫文字檔
output = open('data', 'w')
寫二進位檔案
output = open('data', 'wb')
追加寫檔案
output = open('data', 'w+')
寫資料
file_object = open('thefile.txt', 'w')
file_object.write(all_the_text)
file_object.close( )
檔案讀寫入模式全版:
r+具有讀寫屬性,從檔案頭開始寫,保留原檔案中沒有被覆蓋的內容;
w+具有讀寫屬性,寫的時候如果檔案存在,會被清空,從頭開始寫。
r 開啟唯讀檔案,該檔案必須存在。
r+ 開啟可讀寫的檔案,該檔案必須存在。
w 開啟唯寫檔案,若檔案存在則檔案長度清為0,即該檔案內容會消失。若檔案不存在則建立該檔案。
w+ 開啟可讀寫檔案,若檔案存在則檔案長度清為零,即該檔案內容會消失。若檔案不存在則建立該檔案。
a 以附加的方式開啟唯寫檔案。若檔案不存在,則會建立該檔案,如果檔案存在,
寫入的資料會被加到檔案尾,即檔案原先的內容會被保留。
a+ 以附加方式開啟可讀寫的檔案。若檔案不存在,則會建立該檔案,如果檔案存在,
寫入的資料會被加到檔案尾後,即檔案原先的內容會被保留。
#!/usr/bin/env python'''makeTextFile.py -- create text file'''import osls = os.linesep# get filenamefname = raw_input('filename> ')while True:if os.path.exists(fname):print "ERROR: '%s' already exists" % fnameelse:break# get file content (text) linesall = []print "\nEnter lines ('.' by itself to quit).\n"# loop until user terminates inputwhile True:entry = raw_input('> ')if entry == '.':breakelse:all.append(entry)# write lines to file with proper line-endingfobj = open(fname, 'w')fobj.writelines(['%s%s' % (x, ls) for x in all])fobj.close()print 'DONE!'
#簡單文本讀取f = open('text.txt','r')for line in f.readlines():print line.strip() #預設會讀出分行符號,需要用strip() 進行處理
#二進位檔案複製import osf = open('test.jpg','rb')targetFile='test2.jpg'if os.path.isfile(targetFile): os.remove(targetFile)#另存新檔print open('test2.jpg','wb').write(f.read())