python--文件操作

python文件操作步骤

#第一步:调用文件
f=open(r'D:\untitled\venv\Include\blacklist.txt', 'r', encoding='gbk')
#第二部:使用文件
print(f.readlines())
#第三部:关闭文件
f.close()

#python中内置函数with...as可以自动关闭文件:
with open(r'D:\untitled\venv\Include\blacklist.txt', 'r', encoding='utf-8')as f:
    print(f.readlines())

三种调用文件的路径的写法

open(r'D:\untitled\venv\Include\blacklist.txt')  #r --read  只读,代表' '内的字符串没有其他含义不进行转义
open('D:\\untitled\\venv\\Include\\blacklist.txt') # 或者可以使用 \\ 来代替 \ 
open('D:/untitled/venv/Include/blacklist.txt') # 在windows系统使用路径时,可以使用/来代替 \

读(rt)

# 读取模式
# t 读取文本文件(默认值)
# b 读取二进制文件

read按字符/字节读取

# f.read(int)可指定参数int,  ‘rt’ --->参数int代表读取int个字符   'rb'--->参数int代表读取int个字节

with open(r'D:\untitled\venv\Include\blacklist.txt', 'r', encoding='gbk')as f:
    print(f.read())  
...运行结果

艾妮
你好
hello
world

readline按行读取

with open(r'D:\untitled\venv\Include\blacklist.txt', 'r', encoding='gbk')as f:
    print(f.readline(2))

...运行结果

艾妮

readlines把内容以列表形式展现

with open(r'D:\untitled\venv\Include\blacklist.txt', 'r', encoding='gbk')as f:
    print(f.readlines())

...运行结果

['艾妮\n', '你好\n', 'hello\n', 'world\n']

读取大文件

# 读取大文件的方式
file_name = 'demo.txt'

try:
    with open(file_name,encoding='utf-8') as file_obj:
        # 定义一个变量,来保存文件的内容
        file_content = ''
        # 定义一个变量,来指定每次读取的大小
        chunk = 100
        # 创建一个循环来读取文件内容
        while True:
            # 读取chunk大小的内容
            content = file_obj.read(chunk)

            # 检查是否读取到了内容
            if not content:
                # 内容读取完毕,退出循环
                break

            # 输出内容
            # print(content,end='')
            file_content += content

except FileNotFoundError :
    print(f'{file_name} 这个文件不存在!')


print(file_content)

覆盖写(wt)

with open(r'D:\untitled\venv\Include\blacklist.txt', 'w', encoding='utf-8')as f:
    f.write('你好不好')
with open(r'D:\untitled\venv\Include\blacklist.txt', 'r', encoding='utf-8')as f:
    print(f.readlines())

...运行结果

['你好不好']

追加写appand(at)

with open(r'D:\untitled\venv\Include\blacklist.txt', 'a', encoding='utf-8')as f:
    f.write('艾妮'+'\n')
with open(r'D:\untitled\venv\Include\blacklist.txt', 'r', encoding='utf-8')as f:
    print(f.read())

...运行结果

你好不好
艾妮
艾妮
艾妮

(rb,wb,ab)二进制文件

# 读取模式
# t 读取文本文件(默认值)
# b 读取二进制文件

rb  :  read bytes 二进制字节方式读取 
wb  :  write bytes  二进制字节方式覆盖写
ab  :  appand bytes 二进制字节方式追加写

示例:

file_name = 'c:/Users/lilichao/Desktop/告白气球.flac'

# 读取模式
# t 读取文本文件(默认值)
# b 读取二进制文件

with open(file_name , 'rb') as file_obj:
    # 读取文本文件时,size是以字符为单位的
    # 读取二进制文件时,size是以字节为单位
    # print(file_obj.read(100))

    # 将读取到的内容写出来
    # 定义一个新的文件
    new_name = 'aa.flac'

    with open(new_name , 'wb') as new_obj:

        # 定义每次读取的大小
        chunk = 1024 * 100

        while True :
            # 从已有的对象中读取数据
            content = file_obj.read(chunk)

            # 内容读取完毕,终止循环
            if not content :
                break

            # 将读取到的数据写入到新对象中
            new_obj.write(content)

文件的光标移动

# seek() 可以修改当前读取的位置(即移动光标)
# seek()需要两个参数
#     #   第一个 是要切换到的位置
#     #   第二个 计算位置方式
#     #       可选值:
#     #           0 从头计算,默认值
#     #           1 从当前位置计算
#     #           2 从最后位置开始计算

# tell() 方法用来查看当前读取的位置

示例:# tail -f message | grep '404'

import time
with open(r'C:\Users\Administrator.USER-20190512NQ\Desktop\a.txt', 'rb') as f:
    f.seek(0, 2)
    while True:
        data = f.read()
        if b'404' in data:
            print(data.decode('utf-8'))
        else:
            time.sleep(0.2)

文件的其他操作--OS模块

import os
from pprint import pprint

# os.listdir() 获取指定目录的目录结构
# 需要一个路径作为参数,会获取到该路径下的目录结构,默认路径为 . 当前目录
# 该方法会返回一个列表,目录中的每一个文件(夹)的名字都是列表中的一个元素
r = os.listdir()

# os.getcwd() 获取当前所在的目录
r = os.getcwd()

# os.chdir() 切换当前所在的目录 作用相当于 cd
# os.chdir('c:/')

# r = os.getcwd()

# 创建目录
# os.mkdir("aaa") # 在当前目录下创建一个名字为 aaa 的目录

# 删除目录
# os.rmdir('abc')

# open('aa.txt','w')
# 删除文件
# os.remove('aa.txt')

# os.rename('旧名字','新名字') 可以对一个文件进行重命名,也可以用来移动一个文件
# os.rename('aa.txt','bb.txt')
os.rename('bb.txt','c:/users/lilichao/desktop/bb.txt')

pprint(r)

posted @ 2019-06-15 14:35  du-z  阅读(233)  评论(0编辑  收藏  举报