一,open() 函数 处理文件

open函数,该函数用于文件处理

操作文件时,一般需要经历如下步骤:

  • 打开文件
  • 操作文件
一、打开文件

文件句柄 = open('文件路径', '模式')
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
python  学习之open处理文件
1 文件句柄 = open('文件路径','打开模式')

    文件句柄相当于于变量名,文件路径可以写为绝对路径也可以写为相对路径。

文件句柄可以循环 每次1行
for line in 文件句柄:
  文件句柄.write("新文件")
python  学习之open处理文件

 

打开文件的模式有:

  • r ,只读模式【默认】
  • w,只写模式【不可读;不存在则创建;存在则清空内容;】
  • x, 只写模式【不可读;不存在则创建,存在则报错】
  • a, 追加模式【不可读; 不存在则创建;存在则只追加内容;】

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

  • r+, 读写【可读,可写】
  • w+,写读【可读,可写】
  • x+ ,写读【可读,可写】
  • a+, 写读【可读,可写】

 "b"表示以字节的方式操作

  • rb  或 r+b 
  • wb 或 w+b
  • xb 或 w+b
  • ab 或 a+b

 注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型

  

python  学习之open处理文件
文件 hello.txt
Hello Word!
123
abc
456
abc
789
abc
刘建佐

代码 :
f = open("hello.txt",'rb') # 用到b模式的时候 就不能跟 编码了。
data = f.read()
f.close()
print(data)

输出
C:\Python35\python3.exe E:/py_test/s5/open.py
b'Hello Word!\r\n123\r\nabc\r\n456\r\nabc\r\n789\r\nabc\r\n\xe5\x88\x98\xe5\xbb\xba\xe4\xbd\x90'
python  学习之open处理文件

 

python open函数 r 和rb区别

python  学习之open处理文件

 

下面着重讲解下用"+" 同时读写某个文件的操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# r+形式 写的时候在末尾追加,指针移到到最后
# 大家一定要清楚的明白读写的时候指针指向的位置,下面的这个例子一定要懂
# f.tell()   读取指针的位置
# f.seek(0)  设置指针的位置
with open('1.txt','r+',encoding='utf-8') as f:
    print(f.tell())            #打印下 文件开始时候指针指向哪里 这里指向 0
    print(f.read())            #读出文件内容'字符串',
    print(f.tell())            #文件指针指到 9,一个汉子三个字符串,指针是以字符为单位
    f.write('科比')            #写入内容'科比',需要特别注意此时文件指到文件末尾去了
    print(f.read())            #指针到末尾去了,所以读取的内容为空
    print(f.tell())            #指针指到15
    f.seek(0)                  #将指针内容指到 0 位置
    print(f.read())            #因为文件指针指到开头去了,所以可以读到内容 字符串科比
  
# w+形式 存在的话先清空 一写的时候指针到最后
with open('1.txt','w+') as f:
    f.write('Kg')               #1.txt存在,所以将内面的内容清空,然后再写入 'kg'
    print(f.tell())             #此时指针指向2
    print(f.read())             #读不到内容,因为指针指向末尾了
    f.seek(0)
    print(f.read())             #读到内容,因为指针上一步已经恢复到起始位置
      
# a+打开的时候指针已经移到最后,写的时候不管怎样都往文件末尾追加,这里就不再演示了,读者可以自己试一下
# x+文件存在的话则报错,也不演示了

  

 

 

Python文件读取方式

模式 说明
read([size]) 读取文件全部内容,如果设置了size,那么就读取size字节
readline([size]) 一行一行的读取
readlines() 读取到的每一行内容作为列表中的一个元素

 

二、操作

  1 class file(object)
  2     def close(self): # real signature unknown; restored from __doc__
  3         关闭文件
  4         """
  5         close() -> None or (perhaps) an integer.  Close the file.
  6          
  7         Sets data attribute .closed to True.  A closed file cannot be used for
  8         further I/O operations.  close() may be called more than once without
  9         error.  Some kinds of file objects (for example, opened by popen())
 10         may return an exit status upon closing.
 11         """
 12  
 13     def fileno(self): # real signature unknown; restored from __doc__
 14         文件描述符  
 15          """
 16         fileno() -> integer "file descriptor".
 17          
 18         This is needed for lower-level file interfaces, such os.read().
 19         """
 20         return 0    
 21  
 22     def flush(self): # real signature unknown; restored from __doc__
 23         刷新文件内部缓冲区
 24         """ flush() -> None.  Flush the internal I/O buffer. """
 25         pass
 26  
 27  
 28     def isatty(self): # real signature unknown; restored from __doc__
 29         判断文件是否是同意tty设备
 30         """ isatty() -> true or false.  True if the file is connected to a tty device. """
 31         return False
 32  
 33  
 34     def next(self): # real signature unknown; restored from __doc__
 35         获取下一行数据,不存在,则报错
 36         """ x.next() -> the next value, or raise StopIteration """
 37         pass
 38  
 39     def read(self, size=None): # real signature unknown; restored from __doc__
 40         读取指定字节数据
 41         """
 42         read([size]) -> read at most size bytes, returned as a string.
 43          
 44         If the size argument is negative or omitted, read until EOF is reached.
 45         Notice that when in non-blocking mode, less data than what was requested
 46         may be returned, even if no size parameter was given.
 47         """
 48         pass
 49  
 50     def readinto(self): # real signature unknown; restored from __doc__
 51         读取到缓冲区,不要用,将被遗弃
 52         """ readinto() -> Undocumented.  Don't use this; it may go away. """
 53         pass
 54  
 55     def readline(self, size=None): # real signature unknown; restored from __doc__
 56         仅读取一行数据
 57         """
 58         readline([size]) -> next line from the file, as a string.
 59          
 60         Retain newline.  A non-negative size argument limits the maximum
 61         number of bytes to return (an incomplete line may be returned then).
 62         Return an empty string at EOF.
 63         """
 64         pass
 65  
 66     def readlines(self, size=None): # real signature unknown; restored from __doc__
 67         读取所有数据,并根据换行保存值列表
 68         """
 69         readlines([size]) -> list of strings, each a line from the file.
 70          
 71         Call readline() repeatedly and return a list of the lines so read.
 72         The optional size argument, if given, is an approximate bound on the
 73         total number of bytes in the lines returned.
 74         """
 75         return []
 76  
 77     def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
 78         指定文件中指针位置
 79         """
 80         seek(offset[, whence]) -> None.  Move to new file position.
 81          
 82         Argument offset is a byte count.  Optional argument whence defaults to
 83 (offset from start of file, offset should be >= 0); other values are 1
 84         (move relative to current position, positive or negative), and 2 (move
 85         relative to end of file, usually negative, although many platforms allow
 86         seeking beyond the end of a file).  If the file is opened in text mode,
 87         only offsets returned by tell() are legal.  Use of other offsets causes
 88         undefined behavior.
 89         Note that not all file objects are seekable.
 90         """
 91         pass
 92  
 93     def tell(self): # real signature unknown; restored from __doc__
 94         获取当前指针位置
 95         """ tell() -> current file position, an integer (may be a long integer). """
 96         pass
 97  
 98     def truncate(self, size=None): # real signature unknown; restored from __doc__
 99         截断数据,仅保留指定之前数据
100         """
101         truncate([size]) -> None.  Truncate the file to at most size bytes.
102          
103         Size defaults to the current file position, as returned by tell().
104         """
105         pass
106  
107     def write(self, p_str): # real signature unknown; restored from __doc__
108         写内容
109         """
110         write(str) -> None.  Write string str to file.
111          
112         Note that due to buffering, flush() or close() may be needed before
113         the file on disk reflects the data written.
114         """
115         pass
116  
117     def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
118         将一个字符串列表写入文件
119         """
120         writelines(sequence_of_strings) -> None.  Write the strings to the file.
121          
122         Note that newlines are not added.  The sequence can be any iterable object
123         producing strings. This is equivalent to calling write() for each string.
124         """
125         pass
126  
127     def xreadlines(self): # real signature unknown; restored from __doc__
128         可用于逐行读取文件,非全部
129         """
130         xreadlines() -> returns self.
131          
132         For backward compatibility. File objects now include the performance
133         optimizations previously implemented in the xreadlines module.
134         """
135         pass
136 
137 2.x
138 
139 2.x Code
View Code

相关文章: