Other operating a file operation

Other related operations

seek()

Seek (n) to the cursor position n, Note: Mobile unit is byte, if all the Chinese portion utf-8, if a multiple of 3

Usually we use all seek to move to the beginning or end

Move to the beginning: seek (0,0)

Moved to the current position: seek (0,1)

Move to the end: seek (0,2)

Moving a word: seek (3) to move the cursor is moved in bytes

f = open("小娃娃", mode="r+", encoding="utf-8")
f.seek(0) # 光标移动到开头
content = f.read() # 读取内容, 此时光标移动到结尾
print(content)
f.seek(0) # 再次将光标移动到开头
f.seek(0, 2) # 将光标移动到结尾
content2 = f.read() # 读取内容. 什么都没有
print(content2)
f.seek(0) # 移动到开头
f.write("张国荣") # 写入信息. 此时光标在9 中文3 * 3个 = 9
f.flush()
f.close() 
tell()

tell()

Use tell () can help us get what the current cursor position

f = open("小娃娃", mode="r+", encoding="utf-8")
f.seek(0) # 光标移动到开头
content = f.read() # 读取内容, 此时光标移动到结尾
print(content)
f.seek(0) # 再次将光标移动到开头
f.seek(0, 2) # 将光标移动到结尾
content2 = f.read() # 读取内容. 什么都没有
print(content2)
f.seek(0) # 移动到开头
f.write("张国荣") # 写入信息. 此时光标在9 中⽂文3 * 3个 = 9
print(f.tell()) # 光标位置9
f.flush()
f.close()

Modify the file

File Review: Only the contents of the file is read into memory, the modification is completed information, and then delete the source files, the name of the new file name changed to the old file.

import os
with open("../path1/小娃娃", mode="r", encoding="utf-8") as f1,\
open("../path1/小娃娃_new", mode="w", encoding="UTF-8") as f2:
    content = f1.read()
    new_content = content.replace("冰糖葫芦", "⼤白梨")
    f2.write(new_content)
os.remove("../path1/小娃娃") # 删除源文件
os.rename("../path1/小娃娃_new", "小娃娃") # 重命名新文件

Drawbacks: ⼀ times to read the entire contents of memory overflow solution: read line by line and operations

import os
with open("小娃娃", mode="r", encoding="utf-8") as f1,\
open("小娃娃_new", mode="w", encoding="UTF-8") as f2:
    for line in f1:
        new_line = line.replace("大白梨", "冰糖葫芦")
        f2.write(new_line)
os.remove("小娃娃") # 删除源⽂文件
os.rename("小娃娃_new", "小娃娃") # 重命名新文件

with open (operating file name mode, the encoder) as f:
operating
with the open benefits:
1. can open multiple files
2. Close the file can be automatically
---------------- ---------------------------
modify the content of the document:
1. create a new file
2. Place the contents of the file to be replaced
3. replace after the contents of the new file is written
4. change the file name

路径:
    绝对路径: 从磁盘根部进行查找
    相对路径: ../返回上一级  --推荐使用
    转义:
        1."C:\\user\\ner"
        2. r"C:\user\ner"  -- 推荐使用

Guess you like

Origin www.cnblogs.com/luckinlee/p/11620043.html