Python---文件操作

一:文件操作的基本流程

1 打开文件,得到文件句柄并赋值给一个变量

2 通过句柄对文件进行操作

3 关闭文件

例子:(小重山.txt)
昨夜寒蛩不住鸣。
惊回千里梦,已三更。
起来独自绕阶行。
人悄悄,帘外月胧明。
白首为功名,旧山松竹老,阻归程。
欲将心事付瑶琴。
知音少,弦断有谁听。


f = open('小重山') #打开文件  相对路径
data=f.read()#获取文件内容
f.close() #关闭文件

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

二 文件打开模式

 f = open('小重山','w') #打开文件
Character Meaning(字符含义):
    ========= ===============================================================
    'r'       open for reading (default) 打开读模式(默认)
    'w'       open for writing, truncating the file first 打开写模式之前会清空文件原始的内容
    'x'       create a new file and open it for writing 创建一个新文件,并以写的形式打开
    'a'       open for writing, appending to the end of the file if it exists 打开写模式,从文件内容的末尾开始添加
    'b'       binary mode  二进制模式
    't'       text mode (default) 文本模式(默认)
    '+'       open a disk file for updating (reading and writing) 打开磁盘文件以更新(读写模式)
    'U'       universal newline mode (deprecated) 通用换行符文件(不推荐)
    ========= ===============================================================

三 文件具体操作

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 readline(self, *args, **kwargs):
        pass

def readlines(self, *args, **kwargs):
        pass


def tell(self, *args, **kwargs): # real signature unknown 光标的位置
        """
        Current file position.

        Can raise OSError for non seekable files.
        """
        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 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

def flush(self, *args, **kwargs): #可以生成进度条效果
        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 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
##############################################################less usefull
    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 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 seekable(self, *args, **kwargs): # real signature unknown
        """ True if file supports random-access. """
        pass


    def writable(self, *args, **kwargs): # real signature unknown
        """ True if file was opened in a write mode. """
        pass
具体操作函数

 打印所有行,另外第3行后面加上:'end 3'

有两种方法:
f = open('小重山') #打开文件  前提
1for index,line in enumerate(f.readlines()):
#     if index==2:
#         line=''.join([line.strip(),'end 3'])
#     print(line.strip())
2:
count=0
# for line in f: #for内部将f对象做成一个迭代器,用一行取一行
#     if count==3:
#         line=''.join([line.strip(),'end 3'])
#     print(line.strip())
#     count+=1
注:建议采用第二种

f.tell()的用法

 print(f.readline())# 读取一行,readlines读取全部内容,以列表的形式呈现
 print(f.tell())#tell对于英文字符就是占一个,中文字符占三个,区分与read()的不同.

昨夜寒蛩不住鸣。
26

f.seek()的用法

print(f.read(5))#一个中文占三个字符 读取前五个字符
print(f.tell())
f.seek(0)#调整光标的位置
print(f.read(6))#read后不管是中文字符还是英文字符,都统一算一个单位,read(6),此刻就读了6个中文字符

昨夜寒蛩不
15
昨夜寒蛩不住

f.flush(进度条效果)

import time,sys
for i in range(30):
    sys.stdout.write("*")
    sys.stdout.flush() #flush()写进内存一个,保存到磁盘一个
    time.sleep(0.1)

f.truncate()的用法

f = open('小重山','w')
f.truncate()#全部截断
f.truncate(5)#全部截断   在小重山的TXT文件中写内容前边会空出五个字符

f.write()

# f = open('小重山2','w') #打开文件
# f = open('小重山2','a') #打开文件
# f.write('莫等闲1\n')
# f.write('白了少年头2\n')
# f.write('空悲切!3')

r+,w+,a+模式

1:r+模式(从0的位置开始读,写的内容在原始文件内容之后)
f = open('小重山2','r+') #以读写模式打开文件
print(f.read(5))#可读
f.write('hello')
print('------')
print(f.read())

昨夜寒蛩不
------
住鸣。
惊回千里梦,已三更。
起来独自绕阶行。
人悄悄,帘外月胧明。
白首为功名,旧山松竹老,阻归程。
欲将心事付瑶琴。

2:w+模式 (先清空,再读光标之后的内容)
f = open('小重山2','w+') #以写读模式打开文件
print(f.read(5))#什么都没有,因为先格式化了文本
f.write('hello Terry')
print(f.read())#还是read不到
f.seek(0)
print(f.read())

hello Terry

3:a+模式(从原始文件内容的最后开始读)
w+与a+的区别在于是否在开始覆盖整个文件

二进制模式模式

f = open('小重山','rb') #以二进制的形式读文件
f = open('小重山','wb') #以二进制的形式写文件
f.write('hello alvin!'.encode())#b'hello alvin!'就是一个二进制格式的数据,只是为了观看,没有显示成010101的形式


总结: 在py3中,如果你想要字符数据,即用于观看的,则用r模式,这样我f.read到的数据是一个经过decode的unicode数据; 但是如果这个数据我并不需要看,而只是用于传输,比如文件上传,那么我并不需要decode直接传送bytes就好了,所以这个时候用rb模式.

在py3中,有一条严格的线区分着bytes和unicode,比如seek的用法,在py2和py3里都是一个个字节的seek, 但在py3里你就必须声明好了f的类型是rb,不允许再模糊.

建议: 以后再读写文件的时候直接用rb模式,需要decode的时候仔显示地去解码.

第三行后面加一行内容:'hello Terry!'

两种方法:
第一种:
f_read = open('小重山','r') #以读模式打开文件
f_write = open('小重山2','w') #以写模式打开文件
 
count=0
for line in f_read:
     if count==3:
         f_write.write('hello,Terry\n')
    
     else:
         f_write.write(line)
    count+=1

昨夜寒蛩不住鸣。
惊回千里梦,已三更。
起来独自绕阶行。
hello,岳飞
白首为功名,旧山松竹老,阻归程。
欲将心事付瑶琴。

第二种:
if count==3:
    line='hello,Terry\n'
f_write.write(line)
count+=1
注:有同学说,前面不是做过修改了吗? 大哥,刚才是修改内容后print,现在是对文件进行修改!!!

四 关闭文件

1:f.close()

2 with语句

为了避免打开文件后忘记关闭,可以通过管理上下文,即:
with open('log','r') as f:
        pass
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
with open('log1') as obj1, open('log2') as obj2:
    pass 

参考:https://www.cnblogs.com/yuanchenqi/articles/5782764.html

posted @ 2018-06-27 15:59  珠峰上吹泡泡  阅读(223)  评论(0编辑  收藏  举报