python基础之文件操作

文件操作流程

  • 打开文件,得到文件句柄并赋值给一个变量
  • 通过句柄对文件进行操作
  • 关闭文件
test2.txt='''
床前明月光,
疑似地上霜,
举头望明月,
低头思故乡。
'''
f = open(test2.txt) #打开文件
data=f.read()#获取文件内容
f.close() #关闭文件

注意 if in the win,hello文件是utf8保存的,打开文件时open函数是通过操作系统打开的文件,而win操作系统默认的是gbk编码,所以直接打开会乱码,需要f=open('hello',encoding='utf8'),hello文件如果是gbk保存的,则直接打开即可。

文件打开最基本的模式

符号描述
r 以只读的方式打开,系统默认打开方式
w 以写的方式打开,打开前先删除文件里的内容
a 以追加的方式打开文件,只是在末尾位置追加内容

常用方法

  1 def read(self, size=-1): # known case of _io.FileIO.read
  2         """
  3         注意,不一定能全读回来
  4         Read at most size bytes, returned as bytes.
  5 
  6         Only makes one system call, so less data may be returned than requested.
  7         In non-blocking mode, returns None if no data is available.
  8         Return an empty bytes object at EOF.
  9         """
 10         return ""
 11 
 12 def readline(self, *args, **kwargs):
 13         pass
 14 
 15 def readlines(self, *args, **kwargs):
 16         pass
 17 
 18 
 19 def tell(self, *args, **kwargs): # real signature unknown
 20         """
 21         Current file position.
 22 
 23         Can raise OSError for non seekable files.
 24         """
 25         pass
 26 
 27 def seek(self, *args, **kwargs): # real signature unknown
 28         """
 29         Move to new file position and return the file position.
 30 
 31         Argument offset is a byte count.  Optional argument whence defaults to
 32         SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
 33         are SEEK_CUR or 1 (move relative to current position, positive or negative),
 34         and SEEK_END or 2 (move relative to end of file, usually negative, although
 35         many platforms allow seeking beyond the end of a file).
 36 
 37         Note that not all file objects are seekable.
 38         """
 39         pass
 40 
 41 def write(self, *args, **kwargs): # real signature unknown
 42         """
 43         Write bytes b to file, return number written.
 44 
 45         Only makes one system call, so not all of the data may be written.
 46         The number of bytes actually written is returned.  In non-blocking mode,
 47         returns None if the write would block.
 48         """
 49         pass
 50 
 51 def flush(self, *args, **kwargs):
 52         pass
 53 
 54 
 55 def truncate(self, *args, **kwargs): # real signature unknown
 56         """
 57         Truncate the file to at most size bytes and return the truncated size.
 58 
 59         Size defaults to the current file position, as returned by tell().
 60         The current file position is changed to the value of size.
 61         """
 62         pass
 63 
 64 
 65 def close(self): # real signature unknown; restored from __doc__
 66             """
 67             Close the file.
 68 
 69             A closed file cannot be used for further I/O operations.  close() may be
 70             called more than once without error.
 71             """
 72             pass
 73 ##############################################################less usefull
 74     def fileno(self, *args, **kwargs): # real signature unknown
 75             """ Return the underlying file descriptor (an integer). """
 76             pass
 77 
 78     def isatty(self, *args, **kwargs): # real signature unknown
 79         """ True if the file is connected to a TTY device. """
 80         pass
 81 
 82     def readable(self, *args, **kwargs): # real signature unknown
 83         """ True if file was opened in a read mode. """
 84         pass
 85 
 86     def readall(self, *args, **kwargs): # real signature unknown
 87         """
 88         Read all data from the file, returned as bytes.
 89 
 90         In non-blocking mode, returns as much as is immediately available,
 91         or None if no data is available.  Return an empty bytes object at EOF.
 92         """
 93         pass
 94 
 95     def seekable(self, *args, **kwargs): # real signature unknown
 96         """ True if file supports random-access. """
 97         pass
 98 
 99 
100     def writable(self, *args, **kwargs): # real signature unknown
101         """ True if file was opened in a write mode. """
102         pass
操作方法介绍

具体操作

  1 import sys
  2 f = open(sys.path[0] + "\\test2.txt",encoding="utf-8",mode='r')
  3 print("--------------开始readline")
  4 print(f.readline())#从光标开始读取一行
  5 print("--------------开始readline")
  6 print(f.readline())#从光标开始读取一行
  7 print("--------------开始read")
  8 print(f.read())#从光标位置开始读取剩余的内容
  9 print("--------------seek重置光标后")
 10 f.seek(3)#---->以字节为单位,设置光标在第3个字节处
 11 print(f.read(3))#---------》以字符为单位,读取光标后面的三个字符
 12 f.close()
 13 
 14 f = open(sys.path[0] + "\\test2.txt",encoding="utf-8",mode='r')
 15 # 往第三行结尾添加岳飞
 16 for index,line in enumerate(f.readlines()):
 17     if index==2:
 18         line=''.join([line.strip(),'岳飞'])
 19     print(line.strip())
 20 
 21 
 22 f.close()
 23 print("------------------------for in------------------------------------")
 24 #readlines会将所有的数据加载到内存,不推荐使用,推荐使用如下方式:
 25 f = open(sys.path[0] + "\\test2.txt",encoding="utf-8",mode='r')
 26 for index,line in enumerate(f):#这种方式,直接取文件对象本身,一行一行的拿数据
 27     if index==2:
 28         line=''.join([line.strip(),'岳飞2'])
 29     print(line.strip())
 30 f.close()
 31 print("--------------------------tell----------------------------------")
 32 
 33 f = open(sys.path[0] + "\\test2.txt",encoding="utf-8",mode='r')
 34 f.seek(9)##以字节为单位,设置光标在第三个字节处
 35 print(f.tell())##查看光标的位置,这里是按照字节为单位
 36 print(f.readline())
 37 f.close()
 38 print("-----------------------------写操作-------------------------------")
 39 f = open(sys.path[0] + "\\test2.txt",encoding="utf-8",mode='w')
 40 f.write("hello\nworld")#在f.close()之前,仍然保存在内存中,还未写入到文件
 41 f.flush()# 可以实时将内存里的数据写入到文件
 42 f.write("hello2\nworld")
 43 
 44 print("-----------------------进度条--------------")
 45 # -*- coding:utf8 -*-
 46 import sys
 47 for i in range(1, 11):
 48     per = "".join([str((i / 10) * 100), "%"])
 49     str_content = "#" * (i)
 50     sys.stdout.write("\r"+per + str_content)
 51     sys.stdout.flush()
 52     import time
 53     time.sleep(0.5)
 54     i += 1
 55 f.close()
 56 print("----------------------a追加模式------------")
 57 test2_txt='''
 58 昨夜寒蛩不住鸣。
 59 惊回千里梦,已三更。
 60 起来独自绕阶行。
 61 人悄悄,帘外月胧明。
 62 白首为功名,旧山松竹老,阻归程。
 63 欲将心事付瑶琴。
 64 知音少,弦断有谁听。
 65 '''
 66 # 为了避免忘记关闭文件f.close(),可使用以下方式:
 67 with open(sys.path[0] + "\\test2.txt",encoding="utf-8",mode='a') as f:
 68     f.write(test2_txt)#在文件的末尾追加test_txt
 69 with open(sys.path[0] + "\\test2.txt",encoding="utf-8",mode='r') as f:
 70     print(f.read())
 71 
 72 
 73 import sys
 74 test2_txt='''
 75 昨夜寒蛩不住鸣。
 76 惊回千里梦,已三更。
 77 起来独自绕阶行。
 78 人悄悄,帘外月胧明。
 79 白首为功名,旧山松竹老,阻归程。
 80 欲将心事付瑶琴。
 81 知音少,弦断有谁听。'''
 82 print("----------------r+,以读写方式打开--------------------")
 83 with open(sys.path[0] + "\\test2.txt",encoding="utf-8",mode='r+') as f:
 84     f.seek(0)#根据光标位置添加内容
 85     f.write(test2_txt)
 86     print("------------------")
 87     f.seek(0)
 88     print(f.read())
 89 
 90 
 91 import sys
 92 test2_txt='''
 93 昨夜寒蛩不住鸣。
 94 惊回千里梦,已三更。
 95 起来独自绕阶行。
 96 人悄悄,帘外月胧明。
 97 白首为功名,旧山松竹老,阻归程。
 98 欲将心事付瑶琴。
 99 知音少,弦断有谁听。'''
100 print("----------------w+,以读写方式打开--------------------")
101 with open(sys.path[0] + "\\test2.txt",encoding="utf-8",mode='w+') as f:
102     print(f.read(3))#当以w+方式打开文件的时候,文件原内容已被清空,所有没有打印的内容
103     f.write(test2_txt)
104     print("------------------")
105     f.seek(0)
106     print(f.read())
107 
108 import sys
109 test2_txt='''
110 昨夜寒蛩不住鸣。
111 惊回千里梦,已三更。
112 起来独自绕阶行。
113 人悄悄,帘外月胧明。
114 白首为功名,旧山松竹老,阻归程。
115 欲将心事付瑶琴。
116 知音少,弦断有谁听。'''
117 print("----------------a+,以读写方式打开--------------------")
118 with open(sys.path[0] + "\\test2.txt",encoding="utf-8",mode='a+') as f:
119     print(f.tell())
120     f.seek(0)
121     print(f.tell())
122     print(f.read(3))
123     f.write(test2_txt)
124     print("------------------")
125     f.seek(0)
126     print(f.read())
127 
128 # r+和w+的区别在于w+一开始就清空了原数据,必须先write了之后才会有数据
129 
130 # a+和w+的区别在于w+一开始就清空了原数据,必须先write了之后才会有数据
具体操作

 

posted @ 2017-08-27 15:14  ForeverPine  阅读(207)  评论(0)    收藏  举报
TOP