python3 文件系统 open, close, write 方法

文件系统

基本格式

fs = open('filename')
f = fs.read()
f = fs.write()
fs.close()

fs.close 一定要把文件关闭,否则无法保存

读取文件 open() 函数

用于打开一个文件,返回一个 file 对象,之后用相关的方法进行读写。

open(name[, mode[, buffering]])

name : 一个包含了你要访问的文件名称的字符串值。

mode : mode 决定了打开文件的模式:只读,写入,追加等。参数是非强制的,默认文件访问模式为只读(r)。

buffering : 如果 buffering 的值被设为 0,就不会有寄存。如果 buffering 的值取 1,访问文件时会寄存行。如果将 buffering 的值设为大于 1 的整数,表明了这就是的寄存区的缓冲大小。如果取负值,寄存区的缓冲大小则为系统默认。

文件打开模式 mode

常用的是 r 只读,w 写入,a 追加写入,b 二进制模式。 计算机是二进制传输数据,制定模式的时候最好是带上 b,比如 ab,wb等等 =大师兄python

    'r'       open for reading (default) 文件指针会在文件开头。默认模式

    'w'       open for writing, truncating the file first,只用于写入。如文件已存在,write 会覆盖全部文件,类似 linux 的 echo > filename,若文件不存在,创建文件。

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

    'ab'      以二进制格式打开一个文件用于追加写入。
fs = open('1.txt')
f = fs.read()

print(type(f))
fs.close()

type(f) 的结果是 str,即文件打开之后,实际上是字符串类型,那么对应的可以使用字符串的各种方法,比如 join,replace,split 等等。

file 的其他方法

write()

f.write(str)
在文件关闭前或缓冲区刷新前,字符串内容存储在缓冲区中,这时你在文件中是看不到写入的内容的。

fs = open('1.txt','w')
fs.write('Content1\n')
fs.write('Content2 {0}\n'.format(str))
fs.write('Content3 %s\n' %str)

writelines()

用于向文件中写入一序列的字符串。换行时需要制定换行符 \n。

f.writelines([str])

str 可以是字符串,也可以是列表的形式传入

fs = open('1.txt', 'w')
print('文件名为: ', fs.name)

name = ['Citizen_Wang\n', 'Uncle Wang\n']
fs.writelines(name)
fs.writelines('Living as your neighbour\nYou better keep your eye on your wife')

fs.close()

报错 TypeError: a bytes-like object is required, not ‘str’,原因是 open() 方法里面的模式,使用的是 ‘wb’,故报错 需要二进制对象,而不是字符串。

解决:open() 方法的模式改为 ‘w’ 即可

flush()

将缓冲区的内容,立刻写入到文件并清空缓冲区。一般情况是在关闭文件的时候将内容从缓冲区清空,在不使用 close 方法的时候,flush 可以将文件写入到文件。

fs = open('filename','wb')
fs.flush()
fs.close()

readlins()

读取所有行,每行都处理成字符串,并返回一个列表。

执行之后,光标位置移动到文件末尾,再次读取的时候,会返回一个空列表

fs = open('filename','rb')
test = fs.readlines()
print(test[0,1])  # 打印返回列表的前两个元素
fs.close()

readline()

从文件中读取 1 行,并且光标移动到下一行。

fs = open('1.txt', 'rb')
print('文件名为: ', fs.name)

f = fs.readline()
print('读取的字符串是: %s' %(f))
print('读取的字符串是: %s' %(f))
print('读取的字符串是: %s' %(f))

fs.close()

next()

python3 中的 file 对象不支持 next 方法,但是可以通过 python3 的内置函数 next() 在循环中调用,返回下一行。
next() 函数参考链接

seek()

移动文件读取的指针到制定位置,即移动光标所在位置

f.seek(offset[, where])

在文件中移动文件指针,从 where(0 代表文件起始位置,1 代表当前位置,2代表文件末尾)偏移 offset 个字节

tell()

返回当前指针在文件中的位置

file.tell(offset[, where])

一般配合 seek 一起使用

with 用法

with open('file_name', 'rb') as f:
    print(f.read())

省略了 close 方法,在文件使用中比较方便。

打印文件全部行数和内容

with open('1.txt', 'rb') as file:
    for line, contents in enumerate(file):
        print(line + 1, contents)

打印指定行的内容

打印第 3 行的内容

with open('1.txt', 'rb') as file:
    for line, contents in enumerate(file):
        if line == 3-1:
            print(contents)

还可以使用 linecache 模块

import linecache
count = linecache.getline('1.txt', 3)
print(count)
    原文作者:Citizen_Wang
    原文地址: https://blog.csdn.net/CityzenOldwang/article/details/78315813
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞