Python学习笔记4

2018-08-28  本文已影响0人  MetaT1an

文件

文件

操作模式

文件指针的定位

f = open("a.txt", "r")      # 当前文件内容:12345678

print(f.tell())         # 获得当前文件指针的位置 0
f.seek(2)               # 向后移动两个单位
print(f.tell())         # 2
print(f.read())         # 345678
print(f.tell())         # 8

# seek(offset, whence=0)
# whence表示指定文件指针所在的位置
# whence=0:文件开始处,offset >= 0
# whence=1:当前的位置,offset is free
# whence=2:文件结尾处,offset <= 0

# 但是对于不带 b的文件操作,whence只能为 0

文件读操作

遍历

# 直接遍历文件
f = open("a.txt", "r")

for i in f:
    print(i, end='')    

# 遍历 readlines()的结果
lines = f.readlines()
for line in f:
    print(line, end='')

文件关闭

其他操作

文件相关案例

import os

# 只读模式,打开要复制的文件
# 追加模式,打开副本文件

scr_file = open("d.txt", "r", encoding="utf-8")
obj_file = open("d_copy.txt", "w", encoding="utf-8")

# 从源文件中读取内容,写入到目标文件

while True:
    content = scr_file.read(1024)   # 如果文件过大,分块写入
    if not content:
        break
    else:
        obj_file.write(content)
        
# 关闭源文件和目标文件
scr_file.close()
obj_file.close()
import os

file_list = os.listdir(".")
res = {}

for file in file_list:
    if "." not in file:     # 排除掉目录
        continue

    appendix = file.split(".")[-1]      # 获得扩展名
    
    if appendix not in res:
        res[appendix] = []
    
    res[appendix].append(file)

print(res)
上一篇 下一篇

猜你喜欢

热点阅读