File operations
Open File
Open (Name[,mode[,buffering]]) The Open function uses a file name as a mandatory parameter, and then returns one. Python 3.5 removes the file () with the open (Somefile.txt, ' R ') as files:do_something (files) With statement and assigns the value to the variable, which can then be manipulated. The file closes automatically after the statement ends, even if the exception causes it to exit.file ModeR #只读模式 (default) W (>) #写模式a (>>) #追加模式b (binary mode, such as: FTP send upload ISO image file, Linux can be ignored, windows to process binary files need to be labeled; can be added to other modes) + (read/write mode, Can be added to other modes) U (indicates that the \ r \ n \ r \ \ \ \ r \ \ \ \ \ \ \ \ \ \ r+ mode is used when reading)Basic File Method:Read File contents#一次性读取所有内容到内存obj. Read () #读取文件中的所有行并将其作为列表返回obj. ReadLines () #一次仅读取一行 (from the current position to the occurrence of a newline character, also read this newline character) Obj.readline ()Write file Contents#写入字符串obj. Write (' content ')
#写入字符串列表 (virtually any sequence and iteration of an object), it writes all the strings to the file. Writelines (list)immediately accessSeek (Offset[,whence]) moves the current position (where it is read and written) to the location defined by offset, Where.offset is a number of bytes (characters), and whence defaults to 0. Indicates that the offset is calculated from the beginning of the file (the offset must be non-negative) whence can be set to 1 (offset can be negative relative to the current position) or 2 (as opposed to the end of file movement)
f = open ('Test2.txt','W') F.write ('01234567890123456789') F.seek (5) F.write ('Hello, world!.') F.close () F= Open ('Test2.txt','R') Line=F.read () print (line) f.close () 01234hello, World!89
Truncate # 截断数据,仅保留指定之前数据
f = open ('test2.txt')
F.seek (4)
all data after F.truncate () #截断f. Seek (4) is retained only before.
F.close ()
Tell returns the location of the current file
f = open ('Test2.txt') F.read (2) F.read (3) Print (F.tell ()) F.close ()
5
#假设文件中包含中文
f = open ('test2.txt ', ' r ', encoding= ' Utf-8 ')
A = F.seek (2) #文件报错, because a kanji account is 3 bytes, seek is shifted by byte
(result, consumed) = Self._buffer_decode (data, self.errors, final)
Unicodedecodeerror: ' Utf-8 ' codec can ' t decode byte 0xbd in position 0:invalid start byte
b = F.read (2) #读取字符, (in previous versions a Chinese character accounted for 3 bytes, a single read of 2 bytes will be garbled)
Print (a)
C = F.tell () #返回值还是按照字节来的.
print (b)
Good 0
4
Close FileObj.close () If you want to make sure that the file is closed, you can use the Try/finally statement and call the Close method in the finally pose.
#Once your file here Try : #Write data to your filefinally: file.close ()
Iterate file contents and file objects
Read (), ReadLine (), ReadLines () are mentioned earlier, and another method is described below Fileinput
When iterating over a larger file, ReadLines () consumes a lot of memory, either using the while loop and ReadLine, and using a for loop to iterate through the rows.
Import Fileinput for inch fileinput.input (filename): #便于遍历多个输入流中的行. print (line)
Functions in the Fileinput module
Input (Files[,inplace[,backup]]) #便于遍历多个输入流中的行
FileName () #返回当前文件的名称
Lineno () #返回当前 (cumulative) Number of rows
Filelineno () #返回当前文件的行数
Isfirst () #检查当前行是否是文件的第一行
Isstding () #检查当前最后一行是否来自sys. stdin
Nextfile () #关闭当前文件, move to the next file
Close () #关闭序列
File iterators
f = open (filename) for in F: print (i) f.close ()
You can perform the same actions on file iterators as normal iterators, such as converting them to a list of strings (list (open)), which achieves the same effect as readlines.
f = open ('Log.txt','W') F.write ('aaa\n') F.write ('bbb\n') F.write ('ccc\n') F.write ('ddd\n') F.close () lines= List (open ('Log.txt') print (lines) ['aaa\n','bbb\n','ccc\n','ddd\n']
Python Learning note under three (Basic article)