Python 文件操作

发布时间: 更新时间: 总字数:376 阅读时间:1m 作者: 分享 复制网址

Python 文件操作

介绍

打开文件,使用 open(文件名[,mode]) 返回一个文件对像。mode:

  • “r”,读模式
  • “w”,写模式
  • “r+",读写模式
f = open('abc.txt')
with open('/path/to/file', 'r') as f:
    # Some Code ...

# 二进制模式打开
f = open('/Users/michael/test.jpg', 'rb')

# codecs模块方便解码
with codecs.open('/Users/michael/gbk.txt', 'r', 'gbk') as f:

文件属性:

f.name # 文件名
f.mode # modes: r, w, a, r+, binary

读取文件内容:

f.read() # get the file
f.read(100) # read 100 bytes
f.readline() # read one line
f.readlines() # read all lines
f.seek(0) # start of file

写入文件:

f.write(“some_content”)

关闭文件:

f.close()
f.flush()

练习

  • sort.py
# -*- coding: utf-8 -*-


# def sort_fun1():
#     result = []
#     with open('./shoes.txt', 'r') as f:
#
#         for line in f.readlines():
#             l = line.rsplit()
#             result.append({
#                 'brand': ' '.join(l[0:-2]),
#                 'color': l[-2],
#                 'size': l[-1]})
#     result.sort(key=lambda x: x['size'])
#     result.sort(key=lambda x: x['brand'])
#     result.sort(key=lambda x: x['color'])
#     for i in result:
#         print i


def sort_fun():
    result = []
    with open('./shoes.txt', 'r') as file:
        for line in file:
            l = line.split(None, 2)
            result.append({'brand': l[0], 'color': l[1], 'size': l[2].strip()})

    result.sort(key=lambda x: x['size'])
    result.sort(key=lambda x: x['brand'])
    result.sort(key=lambda x: x['color'])
    for i in result:
        print i


if __name__ == '__main__':
    sort_fun()
  • shoes.txt
Adidas  orange  43
Nike    black   41
Adidas  black   39
New Balance pink    41
Nike    white   44
New Balance orange  38
Nike    pink    44
Adidas  pink    44
New Balance orange  39
New Balance black   43
New Balance orange  44
最新评论
加载中...
Home Archives Categories Tags Statistics