zoukankan      html  css  js  c++  java
  • Python编程从入门到实践笔记——文件

    Python编程从入门到实践笔记——文件

    #coding=gbk
    #Python编程从入门到实践笔记——文件
    #10.1从文件中读取数据
    #1.读取整个文件
    file_name = 'pi_digits.txt'
    with open(file_name) as file_object:
        contents = file_object.read()
        print(contents)
     
    #关键字with在不再需要访问文件后将其关闭。
    #open(path)打开文件
    #read()读取整个文件的内容
     
    #2.文件路径
    #Linux和OS X中:with open('text_files/filename.text') as file_object:
    #Windows中:with open('text_filesfilename.text') as file_object:
     
    #3.逐行读取
    with open(file_name) as file_object:
        for line in file_object:
            print(line.rstrip())
            
    #4.创建一个包含文件各行内容的列表
    #readlines()从文件中读取每一行,并将其存储在一个列表中
    with open(file_name) as file_object:
        lines = file_object.readlines()
        
    for line in lines:
        print(line.rstrip())
     
    #5.使用文件的内容
    #读取文本文件时候,Python将其中的所有文本都解读为字符串。
    with open(file_name) as file_object:
        lines = file_object.readlines()
     
    pi_string = ''
    for line in lines:
        pi_string += line.rstrip()
     
    print(pi_string)
     
    #6.包含一百万位的大型文件
    #复习一下圆周率:3.14159265358979323846264338327950288419716939937510...
     
    #7.圆周率中包含你的生日吗
    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.")
     
     
    #10.2写入文件
    #1.写入空文件
    #open()第一个实参是要打开的文件名称;第二个实参是要以写入模式打开这个文件。
    #读取模式(’r‘)(默认)、写入模式(’w‘)、附加模式(’a‘)、读写模式(’r+‘)
    #Python只能将字符串写入文本文档。要存储数值,可使用str()以后写入
    file_name = 'programming.txt'
     
    with open(file_name, 'w') as file_object:
        file_object.write("I love programming.")
     
    #2.写入多行
    #在write()语句中加入换行符’
    ‘
     
    #3.附加到文件
    #附加模式’a‘
    with open(file_name, 'a') as file_object:
        file_object.write("I love programming.
    ")
        file_object.write("I love playing basketball.
    ")
    由于博主也是在攀登的路上,文中可能存在不当之处,欢迎各位多指教! 如果文章对您有用,那么请点个”推荐“,以资鼓励!
  • 相关阅读:
    java 笔记(2) 接口作为引用数据类型
    linux 笔记(5)让vi或vim显示行数和不显示行数
    linux 笔记(4)Ubuntu 使用时vi编辑器时,不能使用backspace键来进行退格或者不能正常使用
    linux 笔记(3)sudo passwd 设置root用户的密码
    matlab笔记(1) 元胞结构cell2mat和num2cell
    linux 笔记(2) 目录直接强行删除rm -rf *(删除当前目录所有的内容)
    linux 笔记(1) ctrl+c,ctrl+z,ctrl+d
    C51单片机项目:红绿灯
    C51单片机项目:时钟
    java 笔记(1)在子类中,一定要访问父类的有参构造方法?
  • 原文地址:https://www.cnblogs.com/sgh1023/p/10011308.html
Copyright © 2011-2022 走看看