Advanced application files and modified in two ways
First, the advanced application file
Readable, writable
- r + t: readable, writable
- w + t: write, read
- a + t: appendable readable
# wt
with open('36w.txt', 'wt', encoding='utf-8') as fw:
print(fw.readable())
print(fw.writable())
False
True
# w+t
with open('36w.txt', 'w+t', encoding='utf-8') as fw:
print(fw.readable())
print(fw.writable())
True
True
# r+t
with open('36w.txt', 'r+t', encoding='utf-8') as fr:
print(fr.readable())
print(fr.writable())
True
True
File pointer is moved within
Suppose we need to add the contents of a file in the middle row of content, if using a basic r / w / a pattern is very difficult to achieve, so we need to move the pointer within the file.
with open('36r.txt', 'r+t', encoding='utf-8') as fr:
fr.readline()
fr.write('nick 真衰呀') # 写在文件的最后一行
The hard disk has never modify a say on the hard disk only cover that new content covering the new content.
1.seek (offset, whence): offset pointer offset represents the file offset in units of the number of bytes
# seek()
with open('36r.txt', 'rb') as fr:
print(f"fr.seek(4, 0): {fr.seek(4, 0)}") # 0相当于文件头开始;1相当于当前文件所在位置;2相当于文件末尾
# fr.seek(0,2) # 切换到文件末尾
fr.seek(4, 0): 3
2.tell (): Every time statistics are from the beginning of the file to the current position pointer is located
# tell()
with open('36r.txt', 'rb') as fr:
fr.seek(4, 0)
print(f"fr.tell(): {fr.tell()}")
fr.tell(): 4
3.read (n): only read (n) in the mode, n is the number of characters represents, in addition, provided that the other is directed to the number of bytes of the file pointer
# read()
with open('36r.txt', 'rt', encoding='utf-8') as fr:
print(f"fr.read(3): {fr.read(3)}")
fr.read(3): sdf
4.truncate (n): truncate (n) is truncated file, Open file must be written, but can not be opened with w or w +, etc., as directly as empty files, so truncate () To r + or a or under the effect of a + test modes. It's always a reference file header. And truncate () without parameters, corresponding to empty it.
# truncate()
with open('36r.txt', 'ab') as fr:
fr.truncate(2) # 截断2个字节后的所有字符,如果3个字节一个字符,只能截断2/3个字符,还会遗留1/3个字符,会造成乱码