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

    文件读写

    写入测试文件:

    %%writefile test.txt
    this is a test file.
    hello world!
    python is good!
    today is a good day.
    
    Writing test.txt
    

    读文件

    使用 open 函数或者 file 函数来读文件,使用文件名的字符串作为输入参数:

    f = open('test.txt')
    
    f = file('test.txt')
    

    这两种方式没有太大区别。

    默认以读的方式打开文件,如果文件不存在会报错。

    可以使用 read 方法来读入文件中的所有内容:

    text = f.read()
    print text
    
    this is a test file.
    hello world!
    python is good!
    today is a good day.
    

    也可以按照行读入内容,readlines 方法返回一个列表,每个元素代表文件中每一行的内容:

    f = open('test.txt')
    lines = f.readlines()
    print lines
    
    ['this is a test file.
    ', 'hello world!
    ', 'python is good!
    ', 'today is a good day.']
    

    使用完文件之后,需要将文件关闭。

    f.close()
    

    事实上,我们可以将 f 放在一个循环中,得到它每一行的内容:

    f = open('test.txt')
    for line in f:
        print line
    f.close()
    
    this is a test file.
    
    hello world!
    
    python is good!
    
    today is a good day.
    

    删除刚才创建的文件:

    import os
    os.remove('test.txt')
    

    写文件

    我们使用 open 函数的写入模式来写文件:

    f = open('myfile.txt', 'w')
    f.write('hello world!')
    f.close()
    

    使用 w 模式时,如果文件不存在会被创建,我们可以查看是否真的写入成功:

    print open('myfile.txt').read()
    
    hello world!
    

    如果文件已经存在, w 模式会覆盖之前写的所有内容:

    f = open('myfile.txt', 'w')
    f.write('another hello world!')
    f.close()
    print open('myfile.txt').read()
    
    another hello world!
    

    除了写入模式,还有追加模式 a ,追加模式不会覆盖之前已经写入的内容,而是在之后继续写入:

    f = open('myfile.txt', 'a')
    f.write('... and more')
    f.close()
    print open('myfile.txt').read()
    
    another hello world!... and more
    

    写入结束之后一定要将文件关闭,否则可能出现内容没有完全写入文件中的情况。

    还可以使用读写模式 w+

    f = open('myfile.txt', 'w+')
    f.write('hello world!')
    f.seek(6)
    print f.read()
    f.close()
    
    world!
    

    这里 f.seek(6) 移动到文件的第6个字符处,然后 f.read() 读出剩下的内容。

    import os
    os.remove('myfile.txt')
    

    二进制文件

    二进制读写模式 b:

    import os
    f = open('binary.bin', 'wb')
    f.write(os.urandom(16))
    f.close()
    
    f = open('binary.bin', 'rb')
    print repr(f.read())
    f.close()
    
    'x86Hx93xe1xd8xefxc0xaa(x17xa9xc9xa51xf1x98'
    
    import os
    os.remove('binary.bin')
    

    换行符

    不同操作系统的换行符可能不同:

    使用 U 选项,可以将这三个统一看成 换行符。

    关闭文件

    Python中,如果一个打开的文件不再被其他变量引用时,它会自动关闭这个文件。

    所以正常情况下,如果一个文件正常被关闭了,忘记调用文件的 close 方法不会有什么问题。

    关闭文件可以保证内容已经被写入文件,而不关闭可能会出现意想不到的结果:

    f = open('newfile.txt','w')
    f.write('hello world')
    g = open('newfile.txt', 'r')
    print repr(g.read())
    
    ''
    

    虽然这里写了内容,但是在关闭之前,这个内容并没有被写入磁盘。

    使用循环写入的内容也并不完整:

    f = open('newfile.txt','w')
    for i in range(3000):
        f.write('hello world: ' + str(i) + '
    ')
    
    g = open('newfile.txt', 'r')
    print g.read()
    f.close()
    g.close()
    
    hello world: 0
    hello world: 1
    hello world: 2
    ......
    hello world: 2782
    hello world: 2783
    hello world: 2784
    hello world: 2785
    hello world: 2786
    hello world: 2787
    hello world: 2788
    hello world: 2789
    hello world: 2790
    hello world: 2791
    hello 
    
    import os
    os.remove('newfile.txt')
    

    出现异常时候的读写:

    f = open('newfile.txt','w')
    for i in range(3000):
        x = 1.0 / (i - 1000)
        f.write('hello world: ' + str(i) + '
    ')
    
    ---------------------------------------------------------------------------
    
    ZeroDivisionError                         Traceback (most recent call last)
    
    <ipython-input-20-8dc1cc9b29ec> in <module>()
          1 f = open('newfile.txt','w')
          2 for i in range(3000):
    ----> 3     x = 1.0 / (i - 1000)
          4     f.write('hello world: ' + str(i) + '
    ')
    
    
    ZeroDivisionError: float division by zero
    

    查看已有内容:

    g = open('newfile.txt', 'r')
    print g.read()
    f.close()
    g.close()
    
    hello world: 0
    hello world: 1
    hello world: 2
    ......
    hello world: 963
    hello world: 964
    hello world: 965
    hello world: 966
    hello world: 967
    hello world: 968
    hello world: 969
    hell
    

    可以看到,出现异常的时候,磁盘的写入并没有完成,为此我们可以使用 try/except/finally 块来关闭文件,这里 finally 确保关闭文件,所有的写入已经完成。

    f = open('newfile.txt','w')
    try:
        for i in range(3000):
            x = 1.0 / (i - 1000)
            f.write('hello world: ' + str(i) + '
    ')
    except Exception:
        print "something bad happened"
    finally:
        f.close()
    
    something bad happened
    
    g = open('newfile.txt', 'r')
    print g.read()
    g.close()
    
    hello world: 0
    hello world: 1
    hello world: 2
    hello world: 3
    hello world: 4
    hello world: 5
    ......
    hello world: 990
    hello world: 991
    hello world: 992
    hello world: 993
    hello world: 994
    hello world: 995
    hello world: 996
    hello world: 997
    hello world: 998
    hello world: 999
    
    推荐下我自己创建的Python学习交流群`923414804`,这是Python学习交流的地方,不管你是小白还是大牛,都欢迎,不定期分享干货,包括我整理的一份适合零基础学习Python的资料和入门教程。
    

    with 方法

    事实上,Python提供了更安全的方法,当 with 块的内容结束后,Python会自动调用它的close 方法,确保读写的安全:

    with open('newfile.txt','w') as f:
        for i in range(3000):
            x = 1.0 / (i - 1000)
            f.write('hello world: ' + str(i) + '
    ')
    
    ---------------------------------------------------------------------------
    
    ZeroDivisionError                         Traceback (most recent call last)
    
    <ipython-input-24-9d2a70065b27> in <module>()
          1 with open('newfile.txt','w') as f:
          2     for i in range(3000):
    ----> 3         x = 1.0 / (i - 1000)
          4         f.write('hello world: ' + str(i) + '
    ')
    
    
    ZeroDivisionError: float division by zero
    

    try/exception/finally 效果相同,但更简单。

    g = open('newfile.txt', 'r')
    print g.read()
    g.close()
    
    hello world: 0
    hello world: 1
    hello world: 2
    hello world: 3
    ......
    hello world: 994
    hello world: 995
    hello world: 996
    hello world: 997
    hello world: 998
    hello world: 999
    

    所以,写文件时候要确保文件被正确关闭。

    import os
    os.remove('newfile.txt')
    
  • 相关阅读:
    分布式缓存Redis
    MySQL优化
    SYSRET
    SYSCALL
    bolt cms V3.7.0 xss和远程代码执行漏洞
    github渗透测试工具库
    Gradle系列之Gradle插件
    fastjson 漏洞利用 命令执行
    linux 关闭对端口的监听
    微信小程序自动化测试最佳实践(附 Python 源码)
  • 原文地址:https://www.cnblogs.com/paisenpython/p/10266585.html
Copyright © 2011-2022 走看看