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:参考位置为文件末尾


  • 相关阅读:
    TensorFlow 学习(4)——MNIST机器学习进阶
    TensorFlow 学习(3)——MNIST机器学习入门
    TensorFlow 学习(2)——正式起步
    TensorFlow 学习(1)——第一个程序:线性回归
    OpenCV学习笔记(15)——更多的轮廓函数
    OpenCV学习笔记(14)——轮廓的性质
    OpenCV学习笔记(13)——轮廓特征
    OpenCV学习笔记(12)——OpenCV中的轮廓
    机器学习
    机器学习- Attention Model结构解释及其应用
  • 原文地址:https://www.cnblogs.com/gotesting/p/9951355.html
Copyright © 2011-2022 走看看