File IO
#文件的基本操作
1. In Python you can use the file object to do most of the document operations
2. General steps:
First open a file with the Python built-in open () function, and create a Document object,
Then call the relevant method to operate
Grammar:
File_object = open (file_name[,acess_mode][,buffering])
The file_name variable is a string value that contains the name of the file you want to access.
Access_mode determines the mode of opening a file: Read-only, write, append, etc. this parameter is non-mandatory, and the default file access mode is read-only (R)
Buffering: If the value of buffering is set to 0, there will be no deposit. If the buffering value is 1, the file is stored
If the value of buffering is set to an integer greater than 1, it indicates that this is the buffer size of the storage area, and if negative, the buffer size of the storage area is the system default
Full list of open files in different modes:
Properties of the File object
After a file is opened, you have a file object, you can get various information about the files
The following is a list of all properties related to the file object:
File.closed returns True if the file has been closed, otherwise false
File.mode returns the access mode of the file being opened
File.name returns the name of the file
File.softsapce if the print output must be followed by a space character, false is returned, otherwise true
Doc ="D:\python workspace\log.txt"Print("Demo Open") fo= Open (Doc,'W')#W represents writePrint("file name is", Fo.name)Print("whether the file is closed", fo.closed)Print("Open Mode", Fo.mode)Print("\ n Demo Close") fo= Open (Doc,'W')Print("file name is", Fo.name)#Close an open filefo.close ()Print("whether the file is closed", fo.closed)Print("\ n Demo Write") fo= Open (Doc,'W') Fo.write ("Good and Bad")#Close an open filefo.close ()" "W to WB, will error TypeError: ' str ' does not support the buffer interface" "Print("\ n Demo Read")#Open a filefo = open (Doc,"r+")#r+ Reading and writingstr =Fo.read ()Print("the content in the file is", str)#Close FileFo.close ()
Results:
The demo open file name is D:\python workspace\log.txt whether to turn off file false Open with W demo close file name is D:\python workspace\log.txt whether to close files True to write the content in the demo read file is good and bad
The file name/T will be escaped with three ways to avoid:
FileName = r "D:\test1\test2\test.txt" plus R
filename = "D:\\test1\\test2\test.txt" plus double \ \
filename = "D:/test1/test2/test.txt" \ Change to/(recommend this)
File location
The 1.tell () method tells you the current location within the file
2.seek (Offset[,where]) method to change the current position
The offset variable is the number of bits you want to move. Where variable top starts to move the reference position
Where 0 means the beginning of the file, this is the default, 1 is the current position; 2 means the end of the file
#Open a fileDoc ="D:/python workspace/log.txt"fo= Open (Doc,"r+") Str=Fo.read ()Print("the contents of the file are:", str)#Find Current LocationPosition =Fo.tell ()Print("Current Position:", Position)#Reposition The pointer again to the beginning of the filePosition =Fo.seek (0,0) str= Fo.read (2)#read two charactersPrint("the contents of the file are:", str) str= Fo.read (-1)#Read all after the cursorPrint("the contents of the file are:", str)#Close an open fileFo.close ()
Results:
the contents of the file are: good and the contents of the file are: Bad Bad and good
Exercise: Open a file in W, write content separately via write and Writelines
File.write (str) writes a string to a file with no return value
File.writelines (Sequence) writes a list of sequence strings to the file and adds a newline character to each line if a line break is required
# open a file doc_1 = " d:/python workspace/log1.txt " fo = open (Doc_1, " w " ) fo.write ( " Try to be afraid of something and not be pregnant. 1 " ) fo.writelines ([ Span style= "COLOR: #800000" > " Try to be afraid of what 1\n , " and not pregnant. 2 " ") # Close file fo.close ()
Write writes a line
Writelines can write multiple lines, with \ n Branch
Results:
Open the file in w+ mode, write two lines of data, read the entire contents of the file
doc_2 ="D:/python workspace/log2.txt"fo= Open (doc_2,"w+") Fo.writelines (["Try to be afraid of what 1\n","She's not pregnant. 2"])#View Current LocationPosition =Fo.tell ()Print("Current Position:", Position)#Reset Location#Reposition The pointer again to the beginning of the filePosition =Fo.seek (0,0)#Read FileSTR1 =Fo.read ()Print(STR1)
#readlins () read-out is a list#str2 = Fo.readlines ()
#for I in str2:
# Print (i)
#Close FileFo.close ()
The first time I wrote it, I found that I was playing empty,
Add to find the current position statement, found that after writing, the cursor at the bottom, so reset to the initial position, then read out all the files
Results:
Current Position: 24
Try to be afraid of what 1
She's not pregnant. 2
Empty a file
File.truncate ([size]): Intercepts the file, the truncated bytes are pinned by size, and the current extra year position is assumed by default
If no size is specified, it is intercepted from the current location and is equivalent to deleting the
Python Basics-Text manipulation