zoukankan      html  css  js  c++  java
  • python杂记-2(python之文件)

    文件打开函数:f = open

                 表1-1:open函数中模式参数常用值

    打开模式 描述
    ‘r’ 读模式
    ‘w’ 写模式
    ‘a’ 追加模式
    ‘b’ 二进制模式
    ‘+‘ 读/写模式

                    表1-2:文件对象方法

    文件对象方法 执行操作
    f.close() 关闭文件
    f.read(size = -1) 从文件中读取size个字符,当未给定size或给定负值的时候,读取剩余的所有字符,然后作为字符串返回
    f.readline() 以写入模式打开,如果文件存在,则在末尾追加写入
    f.write(str) 将字符串str写入文件
    f.writelines(seq) 向文件写入字符串序列seq,seq应该是一个返回字符串的可迭代对象
    f.seek(offset,from) 在文件中移动文件指针,从from(0代表文件起始位置,1代表当前位置,2代表文件末尾)偏移offset个字节
    f.tell() 返回当前在文件中的位置

    文件读写操作:

    #!/usr/bin/python2
    # -*- coding: utf-8 -*-

    def save_file(boy,girl,count):
    file_name_boy = '/home/wei/wei/test/' + 'boy_' + str(count) + '.txt'
    file_name_girl = '/home/wei/wei/test/' + 'gilr_' + str(count) + '.txt'

    boy_file = open(file_name_boy, 'w')
    girl_file = open(file_name_girl, 'w')

    boy_file.writelines(boy)
    girl_file.writelines(girl)
    boy_file.close()
    girl_file.close()
    def file_split(filename):
    file = open(filename)
    boy = []
    girl = []

    count = 1
    for each_line in file:
    if each_line[:6] != '======':
    (role, line_spoken) = each_line.split(':', 1)
    if role == 'a':
    boy.append(line_spoken)
    if role == 'b':
    girl.append(line_spoken)
    else:
    save_file(boy,girl,count)
    boy = []
    girl = []
    count += 1
    save_file(boy,girl,count)
    file.close()

    file_split(r'/home/wei/wei/test/test.txt')

  • 相关阅读:
    14.9 InnoDB Disk IO and File Space Management InnoDB Disk 和文件空间管理
    haproxy web通过根跳转
    Linux_NIS+NFS+Autofs
    Linux_NIS+NFS+Autofs
    haproxy 配置心跳检查
    14.8.2 Specifying the Row Format for a Table 指定表的Row Format
    14.8.1 Overview of InnoDB Row Storage
    HTML5新增表单之color
    perl vim美化
    14.7.1 Enabling File Formats
  • 原文地址:https://www.cnblogs.com/LS-blog/p/6014733.html
Copyright © 2011-2022 走看看