七、Python-python基础(一)-- 文件操作

一、基本操作

  1:默认打开只读模式

    在普通打开的时候。由于文件的存储是二进制,所以从二进制,转换到 字符串,需要encoding,默认指定encoding = 'uft-8'

   open中第一个参数,可以是一个路径 d:\a.txt,  默认是r模式

1 f = open('a.txt')
2 data = f.read()
3 print(data)

 

 2: 只读模式 r

1 #只读
2 f = open('a.txt','r')
3 data = f.read()
4 print(data)

3:只写模式 w 

   在写之前,先将文件内数据清除,在写 。 不可读。 如果文件不存在则创建。

1 f = open('a.txt','w')
2 f.write('aaa')

4 :不存在写模式 X

     文件不存在,创建后再写,否则报错。 不可读

1 #x模式
2 f = open('b.txt','x')
3 f.write('aaa')

5:追加模式 a

   追加模式,在文件内容最后添加内容。不可读。如果文件不存在,则创建。

1 #a模式
2 f = open('b.txt','a')
3 f.write('bb')

 

6:二进制文件读取方式

    普通打开:python内部将0101010 转换为 字符串

  •     rb二进制打开:不需要python 转换,所以直接读取的到时是二进制的字节。 (普通方式:将二进制字节转换为字符串返回,所以需要指明encoding = 'utf-8')
 1 f = open('a.txt','r')
 2 data = f.read()
 3 print(type(data))
 4 
 5 
 6 f = open('a.txt','rb')
 7 data = f.read()
 8 print(type(data))
 9 
10 
11 C:\Python35\python.exe D:/python/decode.py
12 <class 'str'>
13 <class 'bytes'>

 

  •     wb :二进制,只写。  需要将字符,通过bytes() 转换为字节,01010
1 f = open('b.txt','wb')
2 f.write(bytes('aaa',encoding = 'utf-8'))
  •     xb:二进制只写,文件不存在创建文件,否则报错。
  •     ab:二进制追加只写。

 7:

  • r+   可读可写  :先读后写。写的内容一直在文件末尾。 如果不读直接写。写的内容在文件头会覆盖文件内容。
  • w+  可写可读  :open的时候直接清空文件
  • x+   可写可读  :与w+相比,文件存在报错。
  • a+   可写可读  :打开的同时直接指针到最后。
  • 1 f = open('a.txt','r+')
    2 data = f.read()
    3 print(type(data))
    4 print(data)
    5 
    6 f.write('dddd')
    7 data1 = f.read()  # write 后,指针移动到了文件末尾,所以read不到数据
    8 print(data1)


     1 #w+  先清空,在写的内容才能读到
     2 
     3 f = open('a.txt','w+')
     4 print(f.tell()) #得到当前指针位置
     5 data = f.read() #此处读不到任何内容,因为w+ open的时候回直接清空文件
     6 print(type(data))
     7 print(data)
     8 print(f.tell()) # 得到读取后的指针位置
     9 f.write('中国人')
    10 print(f.tell()) # 得到write后的指针位置
    11 f.seek(2)  # 调整指针位置到2个字节。
    12 data1 = f.read(5) #读取5个字符
    13 print(data1)

    C:\Python35\python.exe D:/python/decode.py
    0
    <class 'str'>

    0
    6
    国人

     1 # a + :打开文件,指针移动文件末尾。 写的时候总是在文件末尾
     2 
     3 f = open('a.txt','a+')
     4 print(f.tell()) #得到当前指针位置
     5 data = f.read() #此处读不到任何内容,因为r+ open的时候指针到最后
     6 f.seek(0)  # #调整指针位置到0
     7 f.write('add') #但是追加还是在文件末尾
     8 f.seek(0)
     9 data1 = f.read()
    10 print(data1)
    11 
    12 
    13 C:\Python35\python.exe D:/python/decode.py
    14 12
    15 中国人中国人add

     

8:指针操作

  • tell() 获得当前指针的位置。 使用字节位置。例如一个汉字 utf-8 下为3个字节。
  • seek() 进行指针位置的偏移 。 使用字节位置。例如一个汉字 utf-8 下为3个字节。
  • 注意下面的read(5)此处表示读取5个字符。不是5好字节。
  •  1 f = open('a.txt','r+')
     2 print(f.tell()) #得到当前指针位置
     3 data = f.read()
     4 print(type(data))
     5 print(data)
     6 print(f.tell()) # 得到读取后的指针位置
     7 f.write('中国人')
     8 print(f.tell()) # 得到write后的指针位置
     9 f.seek(2)  # 调整指针位置到2个字节。
    10 data1 = f.read(5) #读取5个字符
    11 print(data1)
    12 
    13 
    14 C:\Python35\python.exe D:/python/decode.py
    15 0
    16 <class 'str'>
    17 aaa中国人
    18 9
    19 15
    20 a中国人中

     

9 特殊情况 r+ 情况,如果是没有读的时候,先写。会在 0的位置直接写。覆盖掉原来的内容

              如果使用了读取。不管如何,都会在文件末尾进行内容追加。

              如果需要到指定位置进行内容的写入,需要先用seek()调节指针位置,在进行

   

 1 f1 = open('a.txt','r+')
 2 f1.seek(2)
 3 f1.write('gggg')
 4 f1.flush()
 5 data = f1.read()
 6 print(data)
 7 
 8 
 9 ttggggtt11
10 1224
11 12abc
12 lllmmmmm

 

 

二、文件操作

 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     '\n', '\r', and '\r\n'.  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 '\n', '\r', or '\r\n', and
17       these are translated into '\n' 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 '\n' characters written are
24       translated to the system default line separator, os.linesep. If
25       newline is '' or '\n', no translation takes place. If newline is any
26       of the other legal values, any '\n' 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 pass 34 35 def detach(self, *args, **kwargs): # real signature unknown 36 pass 37 38 def fileno(self, *args, **kwargs): # real signature unknown
文件描述符
39 pass 40 41 def flush(self, *args, **kwargs): # real signature unknown
刷新内存
42 pass 43 44 def isatty(self, *args, **kwargs): # real signature unknown 45 pass 46 47 def read(self, *args, **kwargs): # real signature unknown
读取文件内容
48 pass 49 50 def readable(self, *args, **kwargs): # real signature unknown
是否可读
51 pass 52 53 def readline(self, *args, **kwargs): # real signature unknown
仅仅读取一行数据。



f = open('a.txt','r+')
data = f.readline()
print(data)
data1 = f.readline()
print(data1)
data1 = f.readline()
print(data1)



add


123


2345




54 pass 55 56 def seek(self, *args, **kwargs): # real signature unknown
      调整指针的位置
57 pass 58 59 def seekable(self, *args, **kwargs): # real signature unknown
      指针是否可操作 60 pass 61 62 def tell(self, *args, **kwargs): # real signature unknown
        获取当前指针位置
63 pass 64 65 def truncate(self, *args, **kwargs): # real signature unknown
       截取开头 到 指针所在位置的内容
66 pass 67 68 def writable(self, *args, **kwargs): # real signature unknown
       是否可写
69 pass 70 71 def write(self, *args, **kwargs): # real signature unknown
       写操作
72 pass

 

三、循环

1 f = open('a.txt','r+')
2 for line in f:
3     print(line)

 

三 with 操作  管理上下文

 

 使用with 管理上下文,可以不写closed文件,python会自动在with执行完毕后关闭文件,释放资源。

 同时with还可以同时打开2个文件。进行文件读取和写入。

1  with open('a.txt','r+') as f:
2  f.read()
3 
4 
5 with open('a.txt','r+') as f1, open('b.txt','a+') as f2:
6     for lines in f1:
7         f2.write(lines)

 

posted @ 2016-06-04 14:20  咖啡茶  阅读(59)  评论(0)    收藏  举报