python文件操作细节

python文件读写示例

with open(file_w_path, 'r') as f_r:
    with open(file_r_path, 'w') as f_w:
        for line in f_r.readlines():
            f_w.write(line + '
')

覆盖和追加细节

r:只读方式打开文件,缺省默认。
r+:读写方式打开文件。
w:只写方式打开文件,若文件存在以覆盖方式写入,不存在则创建该文件(注意目录无法创建,即指定文件位置的目录不存在会报错)
w+:读写方式代开文件,文件存在则覆盖写入。
a:追加方式打开文件,文件指针会放在文件结尾。
a+:追加读写。

python三种读取文件方式:

  • read()
  • readline()
  • readlines()

然而它们的区别是什么呢,在平时用到时总会遇到,今天总结一下。

0. 前期工作

首先新建一个文件read.txt,用于实际效果举例

Hello
welcome to my world
you are so clever !!!

1. read()

read(size)方法从文件当前位置起读取size个字节,默认(无参数)表示读取至文件结束为止,它的返回为字符串对象

测试程序如下:

import os
with open(os.path.join(os.getcwd(), 'read.txt')) as f:
    content = f.read()
    print(content)
    print(type(content))

这里需要注意两点:

  1. 我用到了os相关操作,即省去了需要输入文件完整路径的麻烦。

  2. 大家要养成with open file as f: 这一习惯,即操作完毕后让其自动关闭文件。

Hello
welcome to my world
you are so clever !!!
<class 'str'>

Process finished with exit code 0

2. readline()

每次只读一行内容,读取时内存占用较少(适用于大文件),它的返回为字符串对象

测试程序:

import os
with open(os.path.join(os.getcwd(), 'read.txt')) as f:
    while True:
         line = f.readline()
         if line:
                print(line)
        else:    
            break

输出结果:

Hello

<class 'str'>

Process finished with exit code 0

3. readlines()

读取文件所有行,保存在列表(list)变量中,列表中每一行为一个元素,它返回的是一个列表对象。

测试程序:

import os
with open(os.path.join(os.getcwd(), 'read.txt')) as f:
    content = f.readlines()
    print(content)
    print(type(content))

输出结果:

['Hello
', 'welcome to my world
', '1234
', 'you are so clever !!!']
<class 'list'>

Process finished with exit code 0

seek

用于移动文件读取指针到指定位置

itertools.islice()

直接读取文件制定行

#读取文件前50行
for line in itertools.islice(f, 50):
    pass

#跳过文件第一行读取文件
for line in itertools.islice(f, 1, None):
    pass
原文地址:https://www.cnblogs.com/wujingqiao/p/9463100.html