Open File
F=open (' note 2.txt','a+', encoding='utf-8 ')
How the file opens--If the open file does not specify a default read mode
R Read mode file does not exist is an error, not writable
r+ read-write mode file does not exist times wrong
W Write mode is unreadable and the content written overwrites the previous content
Content written in w+ write mode overwrites previous content
A + append read-write mode file does not exist is new, readable writable, append does not overwrite
File method
F=open ('Note 2.txt','w+', encoding='Utf-8')#Open FilePrint(F.read ())#Read the filePrint(F.readline ())#Read Only one rowPrint(F.readlines ())#reads all the contents, returns the list, each row is a list elementF.write (names)#write receives only strF.writelines (names)#Writelines An incoming iteration object, including the List,tuple,dictF.seek (0)#seek moves the pointer, but is valid on read, invalid on write, moved after writing or written in the lastF.truncate ()#Empty file ContentsPrint(F.tell ())#View the position of the current file pointer
File pointers
#Question 1F=open ('Note 2.txt','A +', encoding='Utf-8')Print(F.read ())#Question 2F=open ('Note 2.txt','w+', encoding='Utf-8') F.write ('666'+'\ n')Print(F.read ())#Question 3Print(F.readline ())#Read Only one rowPrint(F.readlines ())#Read all the contents, return the list, each row is a list element, read the first line above, then read the pointer to the second line, start reading from the second line
Issue 1: Open Note 2 after read is empty, because the "a +" mode to open the file, the default pointer pointing to the last, so the content can not be read, you need to manually point the pointer to the file start
After the problem 2:write, read is empty, since write points to the end of the file, you need to reopen the file or specify the pointer position
Issue 3: After reading a line, read again, and find that the first line is missing because the pointer is in the second row and starts reading from the second line.
Efficiently process file instances
#内存8G, File 7g, open, put all the content in memory, the memory is full, the computer is jammed
#解决, read a line of processing a row, readline not, because do not know how many times
Fw=open ('lsy.txt', encoding='utf-8')# loop the file object directly, that is, every line in the loop file. for inch FW: =F.strip () nu=f.split (',') print( Nu
Python Basics-File manipulation