One, the read operation of the file
Example 1
1 f = open (' learning ', encoding='utf-8') #首先要打开文件 , or read directly, is not readable 2 data = f.read () #read后的括号里不添加任何东西 3print( Data)4 f.close () #读取完了后一定要记得关闭文件, otherwise the memory will always occupy the memory space of the interactive data, and it is not shut down, it is easily lost, or read by others
Example 2:readline readable
1f = open ('Learning', ' R ', encoding='Utf-8')2 3 Print(F.readable ()) #判断文件是否只读模式4 Print('First line', F.readline (), end="') #因为会空一行, so modify the default values in print5 Print('Second Line', F.readline (), end="') 6 Print('Third line', F.readline ())7 Print('Line Fourth', F.readline ())8 9 Print(F.readlines ()) #因为前面都读完了, the cursor has moved to the end, there is no content to read, so print is empty
1 True 2 First line learning file operations 3 the second line of old boy's tutorial is good 4 line three Hello world 5 6[]
Example 3,readlines: Return is a list form
1 f = open (' learning ', ' R ', encoding='utf-8') 2print (F.readlines ()) #重新打开文件, read all the contents of the file and print it in a list form
1 [' learn file operation \ n' old boy's tutorial good \ n' HelloWorld']
Second, the file write operation
W Mode: This mode will erase the original content when the file is opened.
Example 1
1f = open ('New_file','W', encoding='Utf-8')2F.write ('11111\n')3F.write ('22222\n')4F.write ('33333\n')5F.write ('555\n666\n777\n')6 7 8F.writelines ('11111111\n2222222\n')9F.writelines (['11113331111\n2227772222\n'])Ten #f.writelines ([' 11111111\n2222222\n ', 6]) #报错 file contents can only be strings, only strings can be written One A f.close () - -f = open ('New_file','R', encoding='Utf-8') the Print(F.read ()) -F.close ()
1 11111 2 22222 3 33333 4 555 5 666 6 777 7 11111111 8 2222222 9 11113331111 2227772222
Third, other operations
r+ w+ A +
1 f = open ('new_file','r+', encoding=' Utf-8')2print(F.read (), end=")3 Print(f.write (' I'm a cock-and-wire program ape ')4 f.close ()
1f = open ('New_file','A +', encoding='Utf-8')2 Print(F.read ())3 Print(F.write ('\nhello World'))4 f.close ()5 6f = open ('New_file','R', encoding='Utf-8')7 Print(F.read ())8 9F.close ()
13. The path of Python sedimentation--file operation