python file processing
The file is saved on the hard disk as "010101010101001" in some encoding format on the hard disk.
textpiece ReadTake
1f = open ('Python_file.txt','R', encoding='Utf-8')23 #file path read-only mode to read or write in what encoding4 5data = F.read ()#indicates that all content is read, and that the content is a string that has been converted. 6 7 Print(data)8 9F.close ()#Close File
PS: The encoding here must be the same encoding as the file is set at save time,
Otherwise the "segmentation" will be inaccurate and cause garbled characters.
1f = open ('Python_file.txt','RB')#' RB ' reads in binary mode2 3data =F.read ()4 5 Print(data)#b ' python\xe5\xbe\x88\xe6\xa3\x92 '6 7 Print(Data.decode ())#Python is great.8 9F.close ()
Don't know the code, solve it with Chardet.
1 Import Chardet 2 3 result = Chardet.detect (open ('python_file.txt', mode='RB ' ). Read ())45print(result) #{' encoding ': ' Utf-8 ' , ' confidence ': 0.7525, ' language ': '}
Looping Files
1 f = open ( " python_file , " r ", Encoding=" ) 3 for line in f: 4 5 (line) 6 7 f.close ()
Write
f = open ('Python_file.txt', mode='W', encoding='Utf-8') F.write (' Life was short') f.close () binary write F= Open ('Binary write. txt','WB') F.write ('Life was short, I chose Python'. Encode ('Utf-8'))#represents the write content that must be written to the byte typeF.close ()
Append
Append the content to the end of the file
f = open ("python_file.txt",'a', encoding=" Utf-8") f.write ("Linux is not unix") F.close ()
When the file operation is opened in "a" or "AB" mode, it can only be appended, that is: append content at the end of the original content
When writing to the hard disk, it must be 0101010 of some kind of code,
To be aware when opening:
AB, which needs to be passed directly to a code of 0100101, that is: byte type
A and encoding, a Unicode string is required for writing, and a Unicode string is converted to 010101010 of the encoding based on the encoding that encoding has developed
read/ write mode
f = open ("python_file.txt",'r+', encoding=" Utf-8"#print(data) F.write (" Life was short "# can write f.close ()
read- write mode
f = open ("Pythoner.txt",'w+', encoding="Utf-8") Data=F.read ()Print(data) F.write ("\nnewline 1 python is good") F.write ("\nnewline 2 life are short") F.write ("\nnewline 3 I chose Python") F.write ("\nnewline 4 Linux is not Unix")Print("content", F.read ()) F.close ()
W+ will clear the file first, then write new content, compared to W mode, only support a read function, and can only read the new content has been written
additional functions for file operations
defFileno (self, *args, **kwargs):#Real Signature Unknownreturns the index value of the file handle in the kernel, which can be used after IO multiplexing.defFlush (self, *args, **kwargs):#Real Signature Unknownforcibly flush files from memory buffer to hard diskdefReadable (self, *args, **kwargs):#Real Signature UnknownJudging whether it is readabledefReadLine (self, *args, **kwargs):#Real Signature UnknownRead only one line, encountered \ ror\ n So fardefSeek (self, *args, **kwargs):#Real Signature Unknownmoves the cursor of the action file to the specified position*Note that the length of seek is calculated in bytes, and the character encoding of each character occupies a different length of bytes. such as "Lu Fei Learning City" with GBK deposit is 2 bytes A word, with UTF-8 is 3 bytes, so when opened with GBK, Seek (4The cursor is switched to the middle of "fly" and "learn" two words. But if it's Utf8,seek (4will cause, get the fly this word part of the byte, print the words will be error, because processing the remainder of the text found with UTF8 can't handle, because the code is not up. One byte missing.defSeekable (self, *args, **kwargs):#Real Signature Unknowndetermine if a file is available for seek operationdefTell (self, *args, **kwargs):#Real Signature Unknownreturns the current file action cursor positiondefTruncate (self, *args, **kwargs):#Real Signature Unknowntruncate a file by a specified length*If you specify the length, you can truncate the specified length from the beginning of the file, without specifying the length, and remove everything from the current position to the end of the file. defWritable (self, *args, **kwargs):#Real Signature UnknownDetermine if the file is writable
View Code
Modify a file
Try to open the file directly in r+ mode, the default will append the new content to the last side of the file (the latest test r+ will be overwritten from scratch, the test code below)
F1 = open ("Python_file.txt",'W', encoding='Utf-8') F1.write ("[Yuan Zhen]") f1.close () F2= Open ("Python_file.txt",'r+', encoding="Utf-8")#print (F2.read ()) #先读后写就不会被覆盖, but appendF2.write ('Fade_walk') F2.close ()
Seek, the content will be appended to the last side, because, when the file is opened, to write, the cursor will default to the end of the file, and then start writing
f = open ("contact.txt",'r+', encoding="utf-8 ") F.seek (6) f.write ("mysql") f.close ()
But what is inserted after execution overwrites the content behind the insertion
This is the storage principle of the hard disk, when you save the file to the hard disk, on the hard disk zoned a space, save data, and so you next open this file, seek to a location, each change a word, is the original cover off, if you want to insert, is not possible, because the data on the hard disk will not be moved back. So the current situation, you want to insert, but become the old content will be covered out.
Q: But others Word, Vim can modify the file Oh, you can't change the math.
You want to modify of course, is not in the hard disk modification, the contents of all read into memory, the data in memory can be random additions and deletions to change, after the change, the contents of all write back to the hard disk, the original data all covered out. All kinds of text editors like Vim Word are doing this.
If you do not want to occupy memory, can only use another way, is to read the side change, what meaning? Can't you change it? It is not possible to change the original file, but you can open the old file at the same time, generate a new file Ah, the side from the old inside a line of reading, side to the new line of writing, encountered the need to modify the change and then write to the new file, so that in memory has been only one line of content. Will not take up memory. But this also has a disadvantage, that is, although not accounted for the memory, but the drive, each modification, to generate a new file, although after the change, you can overwrite the old, but in the process of change, there are 2 data.
Python file processing