zoukankan      html  css  js  c++  java
  • python

    # -*- coding:utf-8 -*-

    '''
    @project: jiaxy
    @author: Jimmy
    @file: study_文件处理.py
    @ide: PyCharm Community Edition
    @time: 2018-11-13 10:32
    @blog: https://www.cnblogs.com/gotesting/

    '''


    '''
    文件处理 - open:
    '''

    # 1. 打开文件及读取文件
    file1 = open('dirtest2/dirtest3/a.txt')

    '''
    mode的参数设置:
    r : 只读,read
    w : 只写,write :如果文件已存在,清空文件后再写;如果文件不存在,新建文件后再写
    a : 追加:如果文件已存在,追加内容;如果文件不存在,新建文件后再写
    r+ : 覆盖写,从光标位置开始
    w+ :清空写,从光标位置开始
    a+
    '''
    # (1)file.read() 文件读取
    res1 = file1.read(6) # 可以传入指定的长度
    res2 = file1.read() # 不指定长度的话,一次性读完
    print('res1读取的结果是:{}'.format(res1))
    print('res2读取的结果是:{}'.format(res2))
    # (2)file.readline() 按行读取,一次读一行
    file2 = open('dirtest2/dirtest3/a.txt')
    res3 = file2.readline()
    print('res3读取的结果是:{}'.format(res3))
    # (3)file.readlines() 按行读取,一次性读完所有的行,返回值为列表
    res4 = file2.readlines()
    print('res4读取的结果是:{}'.format(res4))
    # (4) file.write() mode = 'w'时:清空文件后再写
    file3 = open('dirtest2/dirtest3/a.txt',mode='w')
    file3.write('D:美美哒')
    file4 = open('dirtest2/dirtest3/b.txt',mode='w')
    file4.write('呵呵哒')
    # (5)file.write mode = 'a'时: 追加
    file5 = open('dirtest2/dirtest3/c.txt',mode='a')
    file5.write('append')
    # (6)file.tell() 获取你当前的光标位置
    print(file5.tell())
    # (7)file.seek(offset,from) 位移光标位置 seek(0,0)移动到起始位置
    # offset:偏移量
    # from:指定开始移动字节的参考位置
    # 0:参考位置为文件开头
    # 1:参考位置为当前所在位置
    # 2:参考位置为文件末尾


  • 相关阅读:
    python正则表达式
    装饰器和生成器和迭代器
    进一步认识函数
    python:关于函数的初认识
    python的 随手记----字符编码与转码
    python:元祖与字典与集合的粗浅认识
    python:模块导入之浅认识
    java socket编程
    Spring框架下的单元测试方法
    ModelDriven机制及其运用
  • 原文地址:https://www.cnblogs.com/gotesting/p/9951355.html
Copyright © 2011-2022 走看看