zoukankan      html  css  js  c++  java
  • Python文件读写

    文件处理

    f= file('poem.txt', 'w')

     # open for 'w'riting模式可以为读模式('r')、写模式('w')或追加模式('a')

    f.write(poem) # write text to file

    f.close()

    f = file('poem.txt')

    # if no mode is specified, 'r'ead mode is assumed by default

    while True:

    line = f.readline()

    if len(line) == 0: # Zero length indicates EOF

    break

    print line,

    # Notice comma to avoid automatic newline added by Python

    f.close() # close the file

    注意,因为从文件读到的内容已经以换行符结尾,所以我们在print语句上使用逗号来消除自动换行

    储存器

    Python提供一个标准的模块,称为pickle。使用它你可以在一个文件中储存任何Python对象,之后你又可以把它完整无缺地取出来。这被称为 持久地 储存对象。

    还有另一个模块称为cPickle,它的功能和pickle模块完全相同,只不过它是用C语言编写的,因此要快得多(比pickle快1000倍)。你可以使用它们中的任一个,而我们在这里将使用cPickle模块。记住,我们把这两个模块都简称为pickle模块。

    import cPickle as p

    shoplistfile = 'shoplist.data'

    # the name of the file where we will store the object

    shoplist = ['apple', 'mango', 'carrot']

    # Write to the file

    f = file(shoplistfile, 'w')

    p.dump(shoplist, f) # dump the object to a file把对象储存到打开的文件中

    f.close()

    del shoplist # remove the shoplist

    # Read back from the storage

    f = file(shoplistfile)

    storedlist = p.load(f)

    print storedlist

  • 相关阅读:
    Quartz 基本概念及原理
    quartz-2.2.x 快速入门 (1)
    hive踩过的小坑
    spring profile 多环境配置管理
    win10窗口设置眼睛保护色
    优雅地在markdown插入图片
    Using Spring Boot without the parent POM
    isDebugEnabled作用
    Log 日志级别
    为什么要使用SLF4J而不是Log4J
  • 原文地址:https://www.cnblogs.com/manhua/p/3848034.html
Copyright © 2011-2022 走看看