• python-文件基本操作(一)


    一、打开文件的方法:

    fp=file("路径","模式")
    fp=open("路径","模式")
    

    注意:file()和open()基本相同,且最后要用close()关闭文件。 在python3中,已经没了file()这种方法

    二、操作文件的模式:

    打开文件有以下几种模式:

      r :以只读方式打开文件

      w:打开一个文件,只用于写。如果该文件已存在,则会覆盖,如果文件不存在,则会创建一个新文件

      a:打开一个文件,用于追加。如果文件已存在,文件指针会放在文件末尾,如果文件不存在,则会创建一个新文件

    三、写文件操作

    #代码
    fp=open('info','w')
    fp.write('this is the first line')
    fp.write('this is the second line')
    fp.write('this is the third line')
    f.close()
    
    #文件内容结果
    this is the first linethis is the second linethis is the third line
    

      

    注:在写的过程中,内容不会自动换行,如想换行,需要在每个write()中加入" ",如

    #代码
    fp=open('info','w')
    fp.write('this is the first line
    ')
    fp.write('this is the second line
    ')
    fp.write('this is the third line
    ')
    f.close()
    
    #文件内容结果
    this is the first line
    this is the second line
    this is the third line

      

    四、读文件操作

    一次性读取所有read() 

    >>> fp=open('info.log','r')
    >>> print fp.read()
    >>> fp.close() this is the first line this is the second line this is the third line

    ②一次性读取所有,且把结果放入元组中readlines() 

    >>> fp=open('info.log','r')
    >>> print fp.readlines()
    >>> fp.close() ['this is the first line ', 'this is the second line ', 'this is the third line ']

    ③读取一行readline()

    >>> fp=open('info.log','r')
    >>> print fp.readline()
    >>> fp.close()
    this is the first line 
      
    

    循环读取内容

    >>> fp=file('info.log','r')
    >>> for line in fp:
    >>>     print line
    >>> fp.close()
    this is the first line 
    
    this is the second line 
    
    this is the third line
    
    #注:文件中的没一行带有"
    "换行,而使用print的时候,也会自动换行,因此输出结果中会有两次换行,如果想要达到只换行一次的效果,在print line后加入","    如:
    >>> print line,
    this is the first line 
    this is the second line 
    this is the third line 
    

    五、追加文件内容

    >>> fp=open('info.log','a')
    >>> f.write('this is the append line
    ')
    >>> f.close()
    this is the first line 
    this is the second line 
    this is the third line 
    this is the append line 
    

      

  • 相关阅读:
    Codeforces 919D:Substring(拓扑排序+DP)
    初学Javascript,写一个简易的登陆框
    学习数据结构之线性表
    用python实现的简易记牌器的demo
    Multiism四阶巴特沃兹低通滤波器的仿真实现
    用python来抓取“煎蛋网”上面的美女图片,尺度很大哦!哈哈
    用Python爬虫爬取“女神吧”上的照片。
    在linux操作系统上进行简单的C语言源码的gcc编译实验
    想学习linux操作系统,于是选择了在win8 虚拟机VM player 里装了Linux版本Centos7
    通过python的urllib.request库来爬取一只猫
  • 原文地址:https://www.cnblogs.com/nizhihong/p/6528439.html
Copyright © 2020-2023  润新知