Python 文件

作者: 赵者也 | 来源:发表于2018-01-26 17:45 被阅读11次
    1. 新建文件 pi_digits.txt 及内容:
    3.1415926535
      8979323846
      2643383279
    
    1. 读取整个文件
    with open("pi_digits.txt") as file_object:
        contents = file_object.read()
        print(contents.rstrip())
    
    1. 逐行读取
    filename = 'pi_digits.txt'
    
    with open(filename) as file_object:
        for line in file_object:
            print(line.rstrip())
    
    1. 将文件各行内容读入列表
    filename = 'pi_digits.txt'
    
    with open(filename) as file_object:
        lines = file_object.readlines()
    
    
    pi_string = ""
    
    for line in lines:
        pi_string += line.strip()
    
    print("pi_string ", pi_string, "length is:", len(pi_string))
    

    实例输出结果:

    实例输出结果
    1. 圆周率值中前一百万位中是否包含你的生日
    filename = 'pi_million_digits.txt'
    
    with open(filename) as file_object:
        lines = file_object.readlines()
    
    pi_string = ""
    
    for line in lines:
        pi_string += line.strip()
    
    birthday = input("Enter your birthday, in the form mmddyy: ")
    
    if birthday in pi_string:
        print("Your birthday appears in the first million digits of pi!")
    else:
        print("Your birthday does not appear in the first million digits of pi.")
    
    1. 写入文件
    filename = 'programming.txt'
    
    with open(filename, 'w') as file_object:
        file_object.write("I love programming 1.\n")
        file_object.write("I love programming 2.")
    
    1. 附加到文件
    filename = 'programming.txt'
    
    with open(filename, 'a') as file_object:
        file_object.write("I love programming 1.\n")
        file_object.write("I love programming 2.\n")
    

    本文参考自 《Python 编程:从入门到实践

    相关文章

      网友评论

        本文标题:Python 文件

        本文链接:https://www.haomeiwen.com/subject/mqdwaxtx.html