zoukankan      html  css  js  c++  java
  • python input and output and cpickle

          文件的输出输入与数据的存储反存储:

          存储模块:pickle 和cPickle (C语言编写,速度远远快于前者),用法与file.write()差不多,引用

    example:import  cPickle as p

    p.dump(data,file)    #file='file.data'

    p.load(file)

    file.close()

           一般有两种输出方法: expression statements 和 print .第三种write()用于文件对象,标准的输出文件可引用sys.stdout.

           print 用法: 

    print x    

    等价于

     import sys

    sys.stdout.write(str(x)+'\n')

    如果这样写:

    import sys

    sys.stdout=open(file)

    print x,y

    这样我们可以将x,y直接输出到文件中,这种方法也叫重定向输出。

    再举一种重定向,不影响后面的print  原始输出流

    f=open(file,'a')

    print >>f,x,y

    x,y输出到文件对象f中,这个表达式只是暂时的重定向输出,后面的print  语句依然是原始输出。

          排版输出两种:1、通过对字符串的各种操作进行输出。参考string

                              2、用str.format()

          Python提供了两种方法将数值转为字符串:repr() or str()

           str():返回一个易读的数据表达式。

           repr():产生一个解释器能读的表达式。

           用于数字,列表和字典时,两个函数返回的结果是一样的,

    for x in range(1, 11):
    ...     print repr(x).rjust(2), repr(x*x).rjust(3),
    ...     # Note trailing comma on previous line
    ...     print repr(x*x*x).rjust(4)
    ...
    1   1    1
    2   4    8
    3   9   27
    4  16   64
    5  25  125
    6  36  216
    7  49  343
    8  64  512
    9  81  729
    10 100 1000

        zfill(),rjust(),ljust(),center()

    >>> '12'.zfill(5)
    '00012'
    >>> '-3.14'.zfill(7)
    '-003.14'
    >>> '3.14159265359'.zfill(5)
    '3.14159265359'

    str.format() :

    >>> print 'We are the {} who say "{}!"'.format('knights', 'Ni')
    We are the knights who say "Ni!"
    

    format()

    >>> print '{0} and {1}'.format('spam', 'eggs')  #后面表示要显示的数组
    spam and eggs
    >>> print '{1} and {0}'.format('spam', 'eggs')
    eggs and spam
    

    If keyword arguments are used in the format() method, their values are referred to by using the name of the argument.

    >>> print 'This {food} is {adjective}.'.format(
    ...       food='spam', adjective='absolutely horrible')
    This spam is absolutely horrible.
    

    Positional and keyword arguments can be arbitrarily combined:

    >>> print 'The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',other='Georg')  #前一个other
    The story of Bill, Manfred, and Georg.
    

    '!s' (apply str()) and '!r' (apply repr()) can be used to convert the value before it is formatted.

    >>> import math
    >>> print 'The value of PI is approximately {}.'.format(math.pi)
    The value of PI is approximately 3.14159265359.
    >>> print 'The value of PI is approximately {!r}.'.format(math.pi)
    The value of PI is approximately 3.141592653589793.
    

    An optional ':' and format specifier can follow the field name. This allows greater control over how the value is formatted. The following example truncates Pi to three places after the decimal.

    >>> import math
    >>> print 'The value of PI is approximately {0:.3f}.'.format(math.pi)
    The value of PI is approximately 3.142.
    

    Passing an integer after the ':' will cause that field to be a minimum number of characters wide. This is useful for making tables pretty.

    >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
    >>> for name, phone in table.items():
    ...     print '{0:10} ==> {1:10d}'.format(name, phone)
    ...
    Jack       ==>       4098
    Dcab       ==>       7678
    Sjoerd     ==>       4127
    

    If you have a really long format string that you don’t want to split up, it would be nice if you could reference the variables to be formatted by name instead of by position. This can be done by simply passing the dict and using square brackets '[]' to access the keys

    >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
    >>> print ('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
    ...        'Dcab: {0[Dcab]:d}'.format(table))
    Jack: 4098; Sjoerd: 4127; Dcab: 8637678
    

    This could also be done by passing the table as keyword arguments with the ‘**’ notation.

    >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
    >>> print 'Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table)
    Jack: 4098; Sjoerd: 4127; Dcab: 8637678
    

    This is particularly useful in combination with the new built-in vars() function, which returns a dictionary containing all local variables.

    For a complete overview of string formatting with str.format(), see Format String Syntax.

    %号:

    >>> import math
    >>> print 'The value of PI is approximately %5.3f.' % math.pi
    The value of PI is approximately 3.142.
    read and write file:
    open() 返回一个文件对象, 有两个参数: open(filename, mode).
    >>> f = open('/tmp/workfile', 'w')
    >>> print f
    <open file '/tmp/workfile', mode 'w' at 80a0960>
    
    astring=f.read(N)  读取之后的N个字节到一个字符串
    output.flush() 把输出缓冲区刷到硬盘

    读取文件内容调用函数f.read(size), 读取的内容以字符串形式返回,参数size 是一个可选数字,当它省略时,读取所有数据并返回,

    文件如果比机器内存大一倍就会出现问题,大部分被读取并返回.当碰到文件结尾时,返回空字符'' .

    >>> f.read() 'This is the entire file.\n' >>> f.read() ''

    f.readline() 从文件里读取一行; 换行符(\n) 在字符串结束的左边,如果文件没有在换行时结束,它将会在文件的最后一行省略掉。

    这使返回值变得很模糊,如果f.readline() 返回一个空字符串表示文件结束,然而一个空行用一个换行符'\n'表示.

    >>> f.readline()
    'This is the first line of the file.\n'
    >>> f.readline()
    'Second line of the file\n'
    >>> f.readline()
    ''
    

    f.readlines() returns a list containing all the lines of data in the file. If given an optional

    parameter sizehint, it reads that many bytes from the file and enough more to complete a line,

    and returns the lines from that. This is often used to allow efficient reading of a large file

    by lines, but without having to load the entire file in memory. Only complete lines will be returned.

    >>> f.readlines()
    ['This is the first line of the file.\n', 'Second line of the file\n']
    

    An alternative approach to reading lines is to loop over the file object. This is memory efficient, fast, and leads to simpler code:

    >>> for line in f:
            print line,
    
    This is the first line of the file.
    Second line of the file
    

    The alternative approach is simpler but does not provide as fine-grained control. Since the two

    approaches manage line buffering differently, they should not be mixed.

    f.write(string) writes the contents of string to the file, returning None.

    >>> f.write('This is a test\n')
    

    To write something other than a string, it needs to be converted to a string first:

    >>> value = ('the answer', 42)
    >>> s = str(value)
    >>> f.write(s)
    

    f.tell() returns an integer giving the file object’s current position in the file, measured in bytes from the beginning of the file. To change the file object’s position, use f.seek(offset, from_what). The position is computed from adding offset to a reference point; the reference point is selected by the from_what argument. A from_what value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point. from_what can be omitted and defaults to 0, using the beginning of the file as the reference point.

    >>> f = open('/tmp/workfile', 'r+')
    >>> f.write('0123456789abcdef')
    >>> f.seek(5)     # Go to the 6th byte in the file
    >>> f.read(1)
    '5'
    >>> f.seek(-3, 2) # Go to the 3rd byte before the end
    >>> f.read(1)
    'd'
    

    When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file. After calling f.close(), attempts to use the file object will automatically fail.

    >>> f.close()
    >>> f.read()
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    ValueError: I/O operation on closed file
    

    It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks:

    >>> with open('/tmp/workfile', 'r') as f:
    ...     read_data = f.read()
    >>> f.closed
    True
    

    File objects have some additional methods, such as isatty() and truncate() which are less frequently used; consult the Library Reference for a complete guide to file objects.


     

  • 相关阅读:
    SQL语句的执行顺序
    凭兴趣求职80%会失败,为什么
    Google Analytics:为链接点击设定事件追踪的方法
    org/hamcrest/SelfDescribing
    Idea使用记录--添加Problems&&解决Autowired报错could not autowire
    RBAC(Role-Based Access Control)基于角色的访问控制
    如何在不同编程语言中获取现在的Unix时间戳(Unix timestamp)?
    记录使用Hibernate查询bean中字段和数据库列类型不匹配问题
    Java添加自定义注解
    JS获取select的值
  • 原文地址:https://www.cnblogs.com/lovemo1314/p/1853798.html
Copyright © 2011-2022 走看看