The built-in open () function creates a Python file object that can be linked as a file on your computer. After you call Open (), you can read and write the relevant external file by calling the method that returns the file object.
Output = open (' C:\spam ', ' W ') #打开文件, mode is write input = open (' C:\spam ', ' R ') #打开文件, pattern is read input = open (' C:\spam ') #同上, the default is ' R '
astring = F.read () #把整个文件读进单一字符串aString中aString = F.read (N) #读取文件的前N个字符, deposited astringastring = F.read Line () #读取一行aString = F.readlines () #读取整个文件, in the string list astring
F.write (astring) #写入aString字符串到f文件f. Writelines (alist) #把列表aList中的所有字符串写入文件f
F.close ()
Other operations:
F.flush () F.seek (N) #修改文件位置到偏移量N处, proceed to the next step for line in F.open (' myfile '): #文件迭代器一行一行的读取 Open (' filename.txt ', encoding= ' latin-1 ') #Python3. Unicode text file (string string) open (' filename.txt ', ' RB ') #Python3.2 binary Byte file (bytes string)
Note: The file data must be a string in the script, and the Write method such as F.write () will not sit for us any string conversion work, we need to manually convert.
>>>line = F.readline () >>>line "[1,2,3]${' a ': 1, ' B ': 2}\n" >>>parts = Split (' $ ') >>> Parts[' [[+] ', ' {' A ': 1, ' B ': 2}\n ']>>>eval (parts[0]) [1,2,3]>>>obj = [eval (p) for p in parts]> >>obj[[1,2,3],{a ': 1, ' B ': 2}]
The pickle module is a high-level tool that allows us to store almost any Python object directly in the file, and does not require us to convert the string. It's like a super-generic data formatting and parsing tool. For example, to store a dictionary in a file, use pickle directly to store it.
>>>d = {' A ': 1, ' B ': 2}>>>f = open (' myfile ', ' WB ') >>>import Pickle
Later when you want to retrieve the dictionary:
>>>pickle.load (F)
In fact, the pickle internally converts the dictionary into a string form.
Python Learning: Files