Home > Article > Backend Development > Python commonly used file reading and writing
Read text file
input = open('data', 'r')
#The second parameter defaults to r
input = open('data')
Read binary file
input = open ('data', 'rb')
Read fixed bytes
file_object = open('abinfile', 'rb')
3. Write file
Write text file
output = open( 'data', 'w')
Write binary file
output = open('data', 'wb')
Append write file
output = open('data', 'w+')
Write data
file_object = open('thefile.txt', 'w')
file_object.write(all_the_text)
file_object.close( )
File read and write mode full version:
r+ has the read-write attribute, and starts writing from the beginning of the file, retaining the content that has not been overwritten in the original file;
w+ has the read-write attribute, and if the file exists during writing, it will be cleared and written from the beginning.
r Open a read-only file, the file must exist.
r+ opens a readable and writable file, the file must exist.
w Open a write-only file. If the file exists, the file length will be cleared to 0, that is, the file content will disappear. If the file does not exist, create the file.
w+ opens a readable and writable file. If the file exists, the file length will be cleared to zero, that is, the file content will disappear. If the file does not exist, create the file.
a Open a write-only file in append mode. If the file does not exist, the file will be created. If the file exists, the data written by
will be added to the end of the file, that is, the original content of the file will be retained.
a+ Open read-write files in append mode. If the file does not exist, the file will be created. If the file exists, the data written by
will be added to the end of the file, that is, the original content of the file will be retained.
#!/usr/bin/env python '''makeTextFile.py -- create text file''' import os ls = os.linesep # get filename fname = raw_input('filename> ') while True: if os.path.exists(fname): print "ERROR: '%s' already exists" % fname else: break # get file content (text) lines all = [] print "\nEnter lines ('.' by itself to quit).\n" # loop until user terminates input while True: entry = raw_input('> ') if entry == '.': break else: all.append(entry) # write lines to file with proper line-ending fobj = 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 os f = open('test.jpg','rb') targetFile='test2.jpg' if os.path.isfile(targetFile): os.remove(targetFile) #另存为 print open('test2.jpg','wb').write(f.read())