The Fansik content of the test file is as follows:
This was line 1
This was line 2
This was line 3
This was line 4
This was line 5
This was line 6
How to manipulate files:
def open (file, mode= ' R ', Buffering=none, Encoding=none, Errors=none, Newline=none, closefd=true):
The file opens in the following manner:
========= ===============================================================
Character meaning
--------- ---------------------------------------------------------------
' r ' Open for reading (default)
' W ' open for writing, truncating the file first
' x ' Create a new file and open it for writing
' A ' open for writing, appending to the end of the file if it exists
' B ' binary mode
' t ' text mode (default)
' + ' open a disk file for updating (reading and writing)
' U ' universal newline mode (deprecated)
========= ===============================================================
file read operation:
f = open ('fansik'r', encoding='UTF8 ' )print(F.read ()) F.close ()
Reads the entire file contents, the result is as follows:
this is line 1
this is line 2
this was line 3
this is line 4
this was line 5
Span style= "font-family: imitation; font-size:18px ">this is line 6
f = open ('fansik' r', encoding='UTF8' )print(F.readline ()) F.close ()
Read the first line of the entire file with the following results:
This was Line 1
f = open ('fansik' r', encoding='UTF8' )print(F.readlines ()) F.close ()
Reads the entire file contents, displayed as a list, with the following results:
[' This was line 1\n ', ' This was line 2\n ', ' This was line 3\n ', ' This is Line 4\n ', ' This is Line 5\n ', ' This is Line 6 ']
Operation of multiple files at the same time (the operation of the file can be without adding f.close ()):
Number =0with Open ('Fansik','R', encoding='UTF8') as F, open ('Fansik1','W', encoding='UTF8') as F1: forLineinchF:number+ = 1ifNumber = = 5: Line="'. Join ([Line.strip (),'fanjinbao\n']) F1.write (line)
The contents of the Fansik1 file are as follows:
This was Line 1
This was line 2
This was line 3
This was line 4
This was line 5fanjinbao
This was line 6
Python Basics-Basic operations for files