day3-python之文件操作(一)

  目录

一、文件操作
  1.1 文件操作基本流程
  1.2 文件编码
  1.3 文件的打开模式
  1.4 上下文管理
  1.5 文件的修改
  1.6 文件操作方法

二、总结






一、文件操作

1.1 文件操作基本流程
1、打开文件,得到文件句柄并赋值给一个变量
2、通过句柄对文件进行操作
3、关闭文件
例1:相对路径读取文件
1 # 1、打开文件,得到文件句柄并赋值给一个变量(file、f_handle、file_handle、f_obj、f1)
2 f1 = open('a.txt',encoding='utf-8',mode='r')
3 # 2、通过句柄对文件进行操作
4 content = f1.read()
5 # 3、关闭文件
6 f1.close()
# 注意:open指令为windows的指令。windows默认编码方式为gbk,linux默认编码方式为utf-8。
例2:绝对路径读取文件
 1 f1 = open('‪D:a.txt', encoding='utf-8', mode='r')
 2 content = f1.read()
 3 print(content)
 4 输出结果:
 5 '''
 6 Traceback (most recent call last):
 7   File "C:/Users/benjamin/python自动化21期/day3/笔记文本.py", line 1, in <module>
 8     f1 = open('D:a.txt', encoding='utf-8')
 9 OSError: [Errno 22] Invalid argument: 'D:x07.txt'
10 '''

解决方法1(推荐):

1 f1 = open(r'D:a.txt', encoding='utf-8')
2 content = f1.read()
3 print(content)

解决方法2(不推荐):

1 f1 = open('D:\a.txt', encoding='utf-8')
2 content = f1.read()
3 print(content)

# 注意:windows默认编码为gbk,Linux默认编码为utf-8,读取文件时,读取编码不同,也会报错。

1.2 文件编码

unicode:简单粗暴,所有的字符都是2Bytes,优点是字符--数字的转换速度快;缺点是占用空间大。
utf-8:精准,可变长,优点是节省空间;缺点是转换速度慢,因为每次转换都需要计算出需要多长Bytes才能够准确表示。

1.内存中使用的编码是unicode,用空间换时间(程序都需要加载到内存才能运行,因而内存应该是越快越好)
2.硬盘中或网络传输用utf-8,保证数据传输的稳定性。

所有程序,最终都要加载到内存,程序保存到硬盘不同的国家用不同的编码格式,但是到内存中我们为了兼容万国(计算机可以运行任何国家的程序原因在于此),统一且固定使用unicode,这就是为何内存固定用unicode的原因,你可能会说兼容万国我可以用utf-8啊,可以,完全可以正常工作,之所以不用肯定是unicode比utf-8更高效啊(uicode固定用2个字节编码,utf-8则需要计算),但是unicode更浪费空间,没错,这就是用空间换时间的一种做法,而存放到硬盘,或者网络传输,都需要把unicode转成utf-8,因为数据的传输,追求的是稳定,高效,数据量越小数据传输就越靠谱,于是都转成utf-8格式的,而不是unicode。

unicode------>encode(编码)-------->utf-8
utf-8---------->decode--------->unicode

day3-python之文件操作(一)

文件从内存刷到硬盘的操作简称存文件
文件从硬盘读到内存的操作简称读文件
乱码:存文件时就已经乱码 或者 存文件时不乱码而读文件时乱码
总结:
无论是何种编辑器,要防止文件出现乱码(请一定注意,存放一段代码的文件也仅仅只是一个普通文件而已,此处指的是文件没有执行前,我们打开文件时出现的乱码)
核心法则就是,文件以什么编码保存的,就以什么编码方式打开

1.3 文件的打开模式
文件句柄 = open('文件路径','模式')
1、打开文件时,需要指定文件路径和以什么方式打开文件。
  • r,只读模式【默认模式,文件必须存在,不存在则抛出异常】
  • w,只写模式【不可读;不存在则创建;存在则清空内容】
  • x,只写模式【不可读;不存在则创建;存在则报错】
  • a,追加模式【可读,不存在则创建;存在则只追加内容】
r模式:
 1 ## r模式:
 2 # read() 全部读出
 3 f1 = open('log1', encoding='utf-8')
 4 content = f1.read()
 5 print(content)
 6 f1.close()
 7 
 8 # read(n) r模式:按照字符读取
 9 f1 = open('log1',encoding='utf-8')
10 content = f1.read(5)
11 print(content)
12 f1.close()
13 
14 # read(n) rb模式:按照字节读取。1个字符3个字节,写4个字节会报错。
15 f1 = open('log1',mode='rb')
16 content = f1.read(3)
17 print(content.decode('utf-8'))
18 f1.close()
19 
20 # readline() 按行读取,读取完,打印空行
21 f1 = open('log1',encoding='utf-8')
22 print(f1.readline())
23 print(f1.readline())
24 f1.close()
25 
26 # readlines() 将文件每一行作为列表的一个元素并返回这个列表
27 f1 = open('log1',encoding='utf-8')
28 print(f1.readlines())
29 f1.close()
30 
31 # for循环 for循环一个文件句柄,在内存中只占用一条的空间
32 f1 = open('log1',encoding='utf-8')
33 for i in f1:
34     print(i)
35 f1.close()
36 
37 # 编码的补充
38 s1 = '中国'
39 s2 = s1.encode('gbk')
40 print(s2)
41 # 输出结果:b'xd6xd0xb9xfa'
42 
43 s1 = b'xd6xd0xb9xfa'
44 s2 = s1.decode('gbk')
45 s3 = s2.encode('utf-8')
46 print(s3)
47 # 输出结果:b'xe4xb8xadxe5x9bxbd'
48 
49 # 简化
50 s1 = b'xd6xd0xb9xfa'.decode('gbk').encode('utf-8')
51 print(s1)
52 # 输出结果:b'xe4xb8xadxe5x9bxbd'

 w模式:

1 ## w模式
2 # 不可读,文件不存在则创建,存在则清空内容,然后再写入。
3 f1 = open('log2',encoding='utf-8',mode='w')
4 f1.write('python是一门高级语言')
5 f1.close()

 a模式:

1 ## a模式
2 # 可读,不存在则创建,存在则只追加内容
3 f1 = open('log2',encoding='utf-8',mode='a')
4 f1.write('
python学习')
5 f1.close()

 2、“+”表示可以同时读写某个文件(就是增加了一个功能)

  • r+,读写【可读,可写】
  • w+,写读【可读,可写】
  • x+,写读【可读,可写】
  • a+,写读【可读,可写】
r+模式:
 1 # r+模式  先读出原文件,然后追加写入
 2 f1 = open('log1',encoding='utf-8',mode='r+')
 3 print(f1.read())
 4 f1.write('666')
 5 f1.close()
 6 
 7 #r+模式  先写后读,正常情况会出错
 8 f1 = open('log1',encoding='utf-8',mode='r+')
 9 f1.write('666')
10 print(f1.read())
11 f1.close()
12 # 原来内容:快快乐乐
13 # 输出内容:快乐乐
14 # 文件内容:666快乐乐
15 # 光标按照字节去运转
16 
17 # r+模式  先写后读,调整光标位置
18 f1 = open('log1',encoding='utf-8',mode='r+')
19 f1.seek(0,2)
20 f1.write('666')
21 f1.seek(0)
22 print(f1.read())
23 f1.close()
24 # 输出内容:快快乐乐666

 w+模式:

1 # w+模式  先写后读,原文件里内容会先删除,然后再写入
2 f1 = open('log2',encoding='utf-8',mode='w+')
3 f1.write('老男孩')
4 f1.seek(0)
5 print(f1.read())
6 f1.close()

 a+模式:

1 # a+模式
2 f1 = open('log2',encoding='utf-8',mode='a+')
3 f1.write('ababababab')
4 f1.seek(0)
5 print(f1.read())
6 f1.close()

 3、“b”表示以字节的方式操作

对于非文本文件,我们只能使用b模式,"b"表示以字节的方式操作(而所有文件也都是以字节的形式存储的,使用这种模式无需考虑文本文件的字符编码、图片文件的jgp格式、视频文件的avi格式)
  • rb
  • wb
  • xb
  • ab
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码
rb模式:
1 # rb模式  按照字节读取
2 f1 = open('log1', mode='rb')
3 content = f1.read(3)
4 print(content.decode('utf-8'))
5 f1.close()

 wb模式:

1 # wb模式
2 f1 = open('log2',mode='wb')
3 f1.write('python语言'.encode('utf-8'))
4 f1.close()

 ab模式:

# ab模式
f1 = open('log2',mode='ab')
f1.write('
python语言'.encode('utf-8'))
f1.close()

 4、以bytes类型操作的读写、写读、写读模式

  • r+b,读写【可读,可写】
  • w+b,写读【可写,可读】
  • x+b,写读【可写,可读】
  • a+b,写读【可写,可读】
    1.4 上下文管理
1 # with open() as:   在循环的时候不能用
2 with open('log1',encoding='utf-8') as f1:
3     print(f1.read())
4 
5 # with open() as:   操作多个文件句柄
6 with open('log1',encoding='utf-8') as f1,
7         open('log2',encoding='utf-8',mode='w') as f2:
8     print(f1.read())
9     f2.write('777')

1.5 文件的修改

1、打开原文件,产生文件句柄
2、创建新文件产生文件句柄
3、读取原文件,进行修改,写入新文件
4、将原文件删除
5、新文件重命名为原文件

文件的数据是存放于硬盘上的,因而只存在覆盖、不存在修改这么一说,我们平时看到的修改文件,都是模拟出来的效果,具体的说有两种实现方式:
方式一:将硬盘存放的该文件的内容全部加载到内存,在内存中是可以修改的,修改完毕后,再由内存覆盖到硬盘(word,vim,nodpad++等编辑器)
方式二:将硬盘存放的该文件的内容一行一行地读入内存,修改完毕就写入新文件,最后用新文件覆盖源文件

 1 # 方式一
 2 import os
 3 with open('file_test',encoding='utf-8') as f1,
 4     open('file_test.bak',encoding='utf-8',mode='w') as f2:
 5    old_content = f1.read()
 6    new_content = old_content.replace('alex','SB')
 7    f2.write(new_content)
 8 os.remove('file_test')
 9 os.rename('file_test.bak','file_test')
10 
11 # 方式二
12 import os
13 with open('file_test',encoding='utf-8') as f1,
14     open('file_test.bak',encoding='utf-8',mode='w') as f2:
15     for line in f1:
16         new_line = line.replace('SB','alex')
17         f2.write(new_line)
18 os.remove('file_test')
19 os.rename('file_test.bak','file_test')

1.6 文件操作方法

1、常用操作方法

read(3):
1. 文件打开方式为文本模式时,代表读取3个字符
2. 文件打开方式为b模式时,代表读取3个字节
其余的文件内光标移动都是以字节为单位的如:seek,tell,truncate
注意:
1. seek有三种移动方式0,1,2,其中1和2必须在b模式下进行,但无论哪种模式,都是以bytes为单位移动的

seek控制光标的移动,是以文件开头作为参照的

tell当前光标的位置
2. truncate是截断文件,所以文件的打开方式必须可写,但是不能用w或w+等方式打开,因为那样直接清空文件了,所以truncate要在r+或a或a+等模式下测试效果。

 1 # readable()  判断是否可读
 2 f1 = open('log2',encoding='utf-8',mode='w')
 3 print(f1.readable())
 4 f1.write('ababababab')
 5 f1.close()
 6 # 输出结果:False
 7 
 8 # writable()  判断是否可写
 9 f1 = open('log2',encoding='utf-8',mode='w')
10 print(f1.writable())
11 f1.write('ababababab')
12 f1.close()
13 # 输出结果:True
14 
15 # tell  告知指针的位置
16 f1 = open('log2',encoding='utf-8',mode='w')
17 f1.write('ababababab')
18 print(f1.tell())
19 f1.close()
20 # 输出结果:10
21 
22 # seek(参数)  按照字节去调整
23 # seek(0,2)   调至最后位置
2、所有操作方法
  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
View Code
  1 class TextIOWrapper(_TextIOBase):
  2     """
  3     Character and line based layer over a BufferedIOBase object, buffer.
  4     
  5     encoding gives the name of the encoding that the stream will be
  6     decoded or encoded with. It defaults to locale.getpreferredencoding(False).
  7     
  8     errors determines the strictness of encoding and decoding (see
  9     help(codecs.Codec) or the documentation for codecs.register) and
 10     defaults to "strict".
 11     
 12     newline controls how line endings are handled. It can be None, '',
 13     '
', '
', and '
'.  It works as follows:
 14     
 15     * On input, if newline is None, universal newlines mode is
 16       enabled. Lines in the input can end in '
', '
', or '
', and
 17       these are translated into '
' before being returned to the
 18       caller. If it is '', universal newline mode is enabled, but line
 19       endings are returned to the caller untranslated. If it has any of
 20       the other legal values, input lines are only terminated by the given
 21       string, and the line ending is returned to the caller untranslated.
 22     
 23     * On output, if newline is None, any '
' characters written are
 24       translated to the system default line separator, os.linesep. If
 25       newline is '' or '
', no translation takes place. If newline is any
 26       of the other legal values, any '
' characters written are translated
 27       to the given string.
 28     
 29     If line_buffering is True, a call to flush is implied when a call to
 30     write contains a newline character.
 31     """
 32     def close(self, *args, **kwargs): # real signature unknown
 33         关闭文件
 34         pass
 35 
 36     def fileno(self, *args, **kwargs): # real signature unknown
 37         文件描述符  
 38         pass
 39 
 40     def flush(self, *args, **kwargs): # real signature unknown
 41         刷新文件内部缓冲区
 42         pass
 43 
 44     def isatty(self, *args, **kwargs): # real signature unknown
 45         判断文件是否是同意tty设备
 46         pass
 47 
 48     def read(self, *args, **kwargs): # real signature unknown
 49         读取指定字节数据
 50         pass
 51 
 52     def readable(self, *args, **kwargs): # real signature unknown
 53         是否可读
 54         pass
 55 
 56     def readline(self, *args, **kwargs): # real signature unknown
 57         仅读取一行数据
 58         pass
 59 
 60     def seek(self, *args, **kwargs): # real signature unknown
 61         指定文件中指针位置
 62         pass
 63 
 64     def seekable(self, *args, **kwargs): # real signature unknown
 65         指针是否可操作
 66         pass
 67 
 68     def tell(self, *args, **kwargs): # real signature unknown
 69         获取指针位置
 70         pass
 71 
 72     def truncate(self, *args, **kwargs): # real signature unknown
 73         截断数据,仅保留指定之前数据
 74         pass
 75 
 76     def writable(self, *args, **kwargs): # real signature unknown
 77         是否可写
 78         pass
 79 
 80     def write(self, *args, **kwargs): # real signature unknown
 81         写内容
 82         pass
 83 
 84     def __getstate__(self, *args, **kwargs): # real signature unknown
 85         pass
 86 
 87     def __init__(self, *args, **kwargs): # real signature unknown
 88         pass
 89 
 90     @staticmethod # known case of __new__
 91     def __new__(*args, **kwargs): # real signature unknown
 92         """ Create and return a new object.  See help(type) for accurate signature. """
 93         pass
 94 
 95     def __next__(self, *args, **kwargs): # real signature unknown
 96         """ Implement next(self). """
 97         pass
 98 
 99     def __repr__(self, *args, **kwargs): # real signature unknown
100         """ Return repr(self). """
101         pass
102 
103     buffer = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
104 
105     closed = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
106 
107     encoding = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
108 
109     errors = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
110 
111     line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
112 
113     name = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
114 
115     newlines = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
116 
117     _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
118 
119     _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
120 
121 3.x
122 
123 3.x
View Code

 day3-python之文件操作(一)

二、总结

# 打开文件
# f = open('文件路径') 默认的打开方式r ,默认的打开编码是操作系统的默认编码
# r w a (r+ w+ a+) 以上6种加b ,如果打开模式+b,就不需要指定编码了。r+ w+ a+ 工作中避免用这三个。主要用r w a 模式。
# 常用编码:UTF-8 、 gbk
# 操作文件
# 读
# read 不传参数 意味着读所有
# 传参,如果是r方式打开的,参数指的是读多少个字符
# 传参,如果是rb方式打开的,参数指的是读多少个字节
# readline
# 一行一行读 每次只读一行,不会自动停止
# for循环的方式
# 一行一行读 从第一行开始 每次读一行 读到没有之后就停止
# readlines 不常用
# 写
# write 写内容(不会自己换行,需要收到换行 )
# 关闭文件
# f.close()
# with open() as f:
# 修改文件 :
# import os
# os.remove
# os.rename