zoukankan      html  css  js  c++  java
  • python file operations

    python_files_operations

    files, file objects
    open(name [, mode [, bufsize]])
    
    eg:
    file = "data.txt"
    f = open(file, 'r')
    f = open(file, 'w')
    
    • 'r':read
    • 'w':write
    • 'a':append
    • 'rb':write binary,在unix中文件都可以当作二进制,所以都用'rb'
    • 'U' or 'rU': 提供通用支持给换行符,可以写跨平台执行的文件

    换行符在windows中为' ', 在unix中为' '

    methods
    • f.read([n]): read at most n bytes
    • f.readline([n]): 每行最多读n个
    • f.readlines([size])
    • f.write(string): 将string写到f中
    • f.writelines(lines)
    • f.close()
    • f.tell(): returns the cur pointer
    • f.seek()

    文件对象的一些属性:

    • f.closed: 如果文件是打开的返回False
    • f.mode
    • f.name
    • f.softspace
    • f.newlines
    • f.encoding

    遍历文件的方式:

    # method 1
    while True:
        line = f.readline()
            if not line:
                break
    
    # method 2
    for line in f:
        # process line
    
    sys.stdin, sys.stout, sys.stderr

    stdin映射到用户的键盘输入,stdout和stderr输出文本到屏幕 eg:

    import sys
    sys.stdout.write("enter your name: ")
    name = sys.stdin.readline()
    

    上面的等价与raw_input():

    name = raw_input("enter your name: ")
    

    raw_input读取的时候不会包括后面的换行符,这点与stdin.readline()不同

    print语句中可以用','来表示不用输出换行符:

    print 1, 2, 3, 4
    #等价与
    print 1,2,
    pirnt 3,4
    
    formatted output
    print "The values are %d %7.5f %s" % (x, y, z)
    print "The values are {0:d} {1:7.5f} {2}".format(x,y,z)
    

    python3里面,print作为一个函数的形式,如下:

    pirnt("the values are", x, y, z, end = '')
    

    如果要重定向输出到文件中,python2中如下:

    f = open("output.txt", "w")
    print >>f, "hello world"
    ...
    f.close()
    

    在python3里面,可以直接通过print()函数完成:

    print("the values are", x,x,z, file = f)
    

    也可以设置元素之间的分隔符:

    print("the values are", x, y, z, sep = ',')
    
    '''的使用

    '''可以用来做一些格式化的输出,如:

    form = """
    Dear %(name)s,
    
    Please send back my %(item)s or pay me $%(amount)0.2f.
                                    Sincerely yours,
                                    Joe Python User
    
    """
    print form % { 
                  'name': 'Mr. Bush',
                  'item': 'blender',
                  'amount': 50.00,
    }
    

    将会输出

    Dear Mr. Bush,
    
    Please send back my blender or pay me $50.00.
                                    Sincerely yours,
                                    Joe Python User
    

    注意第一行'''之后的/表示第一行的那个换行符不要了,否则在前面会多输出一个空行。()里面的关键字将会被替换。

    用format()函数也可以达到同样的效果:

    form = '''
    Dear {name}s,
    
    Please send back my {item}s or pay me ${amount:0.2f}.
                                    Sincerely yours,
                                    Joe Python User
    
    '''
    
    print form.format(name = "Jack", item = "blender", amount = 50)
    

    还有string里面的Template函数:

    import string
    form = string.Template("""
    Dear $name,
    Please send back my $item or pay me $amount.
                        Sincerely yours,
                        Joe Python User
    """)
    print form.substitute({'name': 'Mr. Bush',
    'item': 'blender',
    'amount': "%0.2f" % 50.0})
    

    这里用$表示将要被替换的内容

  • 相关阅读:
    【PAT甲级】1043 Is It a Binary Search Tree (25 分)(判断是否为BST的先序遍历并输出后序遍历)
    Educational Codeforces Round 73 (Rated for Div. 2)F(线段树,扫描线)
    【PAT甲级】1042 Shuffling Machine (20 分)
    【PAT甲级】1041 Be Unique (20 分)(多重集)
    【PAT甲级】1040 Longest Symmetric String (25 分)(cin.getline(s,1007))
    【PAT甲级】1039 Course List for Student (25 分)(vector嵌套于map,段错误原因未知)
    Codeforces Round #588 (Div. 2)E(DFS,思维,__gcd,树)
    2017-3-9 SQL server 数据库
    2017-3-8 学生信息展示习题
    2017-3-5 C#基础 函数--递归
  • 原文地址:https://www.cnblogs.com/jolin123/p/4077598.html
Copyright © 2011-2022 走看看