首页 > 技术文章 > Python 文件操作

JYNNO1 2019-02-24 20:59 原文

 文件操作:

函数:

  open( ['file', "mode='r'", 'buffering=-1', 'encoding=None', 'errors=None', 'newline=None', 'closefd=True', 'opener=None'], )

mode 参数:

  ========= ===============================================================

  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              # 创建新文件 并以写入方式打开 (文件已存在则会异常)The 'x' mode implies 'w' and raises an `FileExistsError` if the file already exists

   '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)

   ========= ===============================================================

  The default mode is 'rt' (open for reading text). For binary random access,

  the mode 'w+b' opens and truncates the file to 0 bytes, while 'r+b' opens the file without truncation.

  The 'x' mode implies 'w' and raises an `FileExistsError` if the file already exists.

通过 open() 函数生成一个文件对象:

  file = open('path','mode',....)

文件对象的操作函数:

  file.close()        #关闭文件

  file.read(size)        #按字节读取 size 长度的文件(负值或空则读完)

  file.readline()                      # Read until newline or EOF  读取一行

  file.readlines()                    # Return a list of lines from the stream. 将文件每一行读出,返回列表

  file.write(str)                       # 将字符串 str 写入

  file.writelines(seq)              # 向文件写入字符串序列seq, seq应该是一个返回字符串的可迭代对象

  file.seek(offset, from)          #在文件中移动指针,从from偏移 offset 个字符

  file.tell()                               #当前文件指针位置

文件未关闭时,当前文件位置指针会一直有效,在读取或写入时,需要注意

将文件转换为列表:

  file = open('path', 'mode')

  file_list = list(file)

  for line in file_list:

    print(line)

  -------------------------------------------------------

直接使用 readlins()函数 file_list = file.readlines()

f = open('file_test.txt')
print(f.readline())                       #读一行数据
print(f.tell())                                # 打印当前位置指针

print(f.readline())                       # 文件未关闭,再次读取时从 当前指针开始读取
print(f.readlines())      # 从读取两次后 指针位置开始读取

f.seek(0,0)                                  # 设置文件位置指针
print(f.readlines())                       #将文件读取为列表
print(f.tell())                               

-------------------------------------------------------------------------------------------------------------------------------

已经崩盘了

12
节能主义

['玫瑰色']
['已经崩盘了\n', '节能主义\n', '玫瑰色']
28

文件内容的处理:字符串的相关内置函数、正则表达

推荐阅读