对文件操作流程

  1. 打开文件,得到文件句柄并赋值给一个变量
  2. 通过句柄对文件进行操作
  3. 关闭文件
 f = open('lyrics') #打开文件
first_line = f.readline()
print('first line:',first_line) #读一行
print('我是分隔线'.center(50,'-'))
data = f.read()# 读取剩下的所有内容,文件大时不要用
print(data) #打印文件 f.close() #关闭文件

  

打开文件的模式有:

  • r,只读模式(默认)。
  • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
  • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+,可读写文件。【可读;可写;可追加】
  • w+,写读
  • a+,同a

"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)

  • rU
  • r+U

"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

  • rb
  • wb
  • ab

其他语法

 def close(self): # real signature unknown; restored from __doc__
"""
Close the file. A closed file cannot be used for further I/O operations. close() may be
called more than once without error.
"""
pass def fileno(self, *args, **kwargs): # real signature unknown
""" Return the underlying file descriptor (an integer). """
pass def isatty(self, *args, **kwargs): # real signature unknown
""" True if the file is connected to a TTY device. """
pass def read(self, size=-1): # known case of _io.FileIO.read
"""
注意,不一定能全读回来
Read at most size bytes, returned as bytes. Only makes one system call, so less data may be returned than requested.
In non-blocking mode, returns None if no data is available.
Return an empty bytes object at EOF.
"""
return "" def readable(self, *args, **kwargs): # real signature unknown
""" True if file was opened in a read mode. """
pass def readall(self, *args, **kwargs): # real signature unknown
"""
Read all data from the file, returned as bytes. In non-blocking mode, returns as much as is immediately available,
or None if no data is available. Return an empty bytes object at EOF.
"""
pass def readinto(self): # real signature unknown; restored from __doc__
""" Same as RawIOBase.readinto(). """
pass #不要用,没人知道它是干嘛用的 def seek(self, *args, **kwargs): # real signature unknown
"""
Move to new file position and return the file position. Argument offset is a byte count. Optional argument whence defaults to
SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
are SEEK_CUR or 1 (move relative to current position, positive or negative),
and SEEK_END or 2 (move relative to end of file, usually negative, although
many platforms allow seeking beyond the end of a file). Note that not all file objects are seekable.
"""
pass def seekable(self, *args, **kwargs): # real signature unknown
""" True if file supports random-access. """
pass def tell(self, *args, **kwargs): # real signature unknown
"""
Current file position. Can raise OSError for non seekable files.
"""
pass def truncate(self, *args, **kwargs): # real signature unknown
"""
Truncate the file to at most size bytes and return the truncated size. Size defaults to the current file position, as returned by tell().
The current file position is changed to the value of size.
"""
pass def writable(self, *args, **kwargs): # real signature unknown
""" True if file was opened in a write mode. """
pass def write(self, *args, **kwargs): # real signature unknown
"""
Write bytes b to file, return number written. Only makes one system call, so not all of the data may be written.
The number of bytes actually written is returned. In non-blocking mode,
returns None if the write would block.
"""
pass

with语句

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

 with open('log','r') as f:

     ...

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:

 with open('log1') as obj1, open('log2') as obj2:
pass

Python3 文件操作基本语法的更多相关文章

  1. python从入门到大神---4、python3文件操作最最最最简单实例

    python从入门到大神---4.python3文件操作最最最最简单实例 一.总结 一句话总结: python文件操作真的很简单,直接在代码中调用文件操作的函数比如open().read(),无需引包 ...

  2. [Python] python3 文件操作:从键盘输入、打开关闭文件、读取写入文件、重命名与删除文件等

    1.从键盘输入 Python 2有两个内置的函数用于从标准输入读取数据,默认情况下来自键盘.这两个函数分别是:input()和raw_input(). Python 3中,不建议使用raw_input ...

  3. Python2与python3 文件操作关于打开文件

    #首先在python3中操作文件只有一种选择,那就是open() #而在python2中则有两种方式:file()与open() 两者都能够打开文件,对文件进行操作,也具有相似的用法和参数,但是,这两 ...

  4. Python3 文件操作(十六)

    一 文件操作 1.介绍 计算机系统分为:计算机硬件,操作系统,应用程序三部分. 我们用python或其他语言编写的应用程序若想要把数据永久保存下来,必须要保存于硬盘中,这就涉及到应用程序要操作硬件,众 ...

  5. python3 文件操作练习 r+ w+ a+ 的理解

    突然来一句:“慨然有经略四方之志” 文件操作三部曲:1.先用open打开 2.再写关闭  3.再回到中间写操作     为啥要刚打开就关闭 那是很容易望,所以先写上... 基本格式 f = open( ...

  6. python3文件操作

    文件操作的过程 1)打开 2)操作 3)关闭 1.写(清空写入) # f = open(file='test', mode='w', encoding='utf-8') # 第一种情况 # f.wri ...

  7. python3 文件操作

    步骤:打开文件->操作文件->关闭文件 打开文件 文件句柄 = open('文件路径', '模式') 指定文件编码 文件句柄= open('文件路径','模式',encoding='utf ...

  8. Python3文件操作1 --Python3

    1.文件的两种类型 文本文件:由单一特定的编码字符组成(如:txt文件) 二进制文件:直接由比特0和比特1组成,文件内部数据组织格式与文件的用途有关(视频.图片) 2.文件主要操作概述 Python对 ...

  9. Python3学习之路~2.7 文件操作

    对文件操作流程 打开文件,得到文件句柄并赋值给一个变量 通过句柄对文件进行操作 关闭文件 现有文件如下 Somehow, it seems the love I knew was always the ...

随机推荐

  1. CSS知识之 background-position 用法详细介绍

    一.语法 background-position : length || length background-position : position || position 二.取值 length   ...

  2. jquery动画切换引擎插件 Velocity.js 学习02

    案例实践: 第一页会以动画形式进入页面: 点击进入按钮时,第一页以动画消失,第二页以动画形式进入,同时四张图片也定义从小到大的动画形式: 第二页关闭按钮点击时,先是四张图片以缩小动画消失,然后第二页以 ...

  3. HTML5实体刮刮乐效果!

    先来看DEMO吧,http://codepen.io/jonechen/pen/ZOyxmq HTML部分: <div class="msg"> <a href= ...

  4. Spring Security 集成CAS实现单点登录

    参考:http://elim.iteye.com/blog/2270446 众所周知,Cas是对单点登录的一种实现.本文假设读者已经了解了Cas的原理及其使用,这些内容在本文将不会讨论.Cas有Ser ...

  5. 【BZOJ2882】工艺 [SAM]

    工艺 Time Limit: 10 Sec  Memory Limit: 128 MB[Submit][Status][Discuss] Description 小敏和小燕是一对好朋友. 他们正在玩一 ...

  6. java springmvc4 图片或文件上传

    1.文件配置 配置文件解析 上传文件处理的核心方法 // uploadOneFile.jsp, uploadMultiFile.jsp submit to. @RequestMapping(value ...

  7. xgboost/gbdt在调参时为什么树的深度很少就能达到很高的精度?

    问题: 用xgboost/gbdt在在调参的时候把树的最大深度调成6就有很高的精度了.但是用DecisionTree/RandomForest的时候需要把树的深度调到15或更高.用RandomFore ...

  8. Arduino 舵机sg90电位器实现转动方向控制

    /* Sweep*/ #include <Servo.h> int potpin = 0;//电位器接到A0 int val; //存储电位器读取的数值 Servo myservo//定义 ...

  9. php中使用static方法

    <?php class Char{ public static $number = 0; public static $name; function __construct($what){ se ...

  10. Linux下通过jstat命令查看jvm的GC情况

    jstat命令可以查看堆内存各部分的使用量,以及加载类的数量.命令的格式如下: jstat [-命令选项] [vmid] [间隔时间/毫秒] [查询次数]  注意!!!:使用的jdk版本是jdk8. ...