读取

一次性读取文件的全部内容 read()

with语句会自动帮我们调用close()方法

要读取非UTF-8编码的文本文件,需要给open()函数传入encoding参数,例如,读取GBK编码的文件:
encoding=’gbk’ # utf-8 / gbk

with open('/path/to/file', 'r', encoding='gbk') as f:
    print(f.read()) #取的全部内容

调用read()会一次性读取文件的全部内容,如果文件有20G,内存就爆了,所以,要保险起见,可以反复调用read(size)方法,每次最多读取size个字节的内容。另外,调用readline()可以每次读取一行内容,调用readlines()一次读取所有内容并按行返回list。因此,要根据需要决定怎么调用。

按行读取文件 readlines()

如果文件很小,read()一次性读取最方便;如果不能确定文件大小,反复调用read(size)比较保险;如果是配置文件,调用readlines()最方便:

例1

with open('/path/to/file', 'r', encoding='gbk') as f:
      for line in f.readlines():
           print(line.strip()) # 把末尾的'\n'删掉

例2

import time
with open("proxy_rule.txt", "r") as f:
    k = 0
    # 按行读文件
    for rule in f.readlines():
        print(k, rule)
        r = rule.rstrip('\n')
        # r = rule.replace('\n', '')
        # 跳过第一行
        if len(r) == 0:
            k += 1
            continue
        k += 1
        fileName = "res/" + str(k) + ".txt"
        # print(fileName)
        time.sleep(0.5)
        print(k, rule)
        #writeFile(fileName, rule)

例3

import json
def readFile():
    with open("威马汽车.json", "r") as f:
        results = ''
        for data in f.readlines():
            dataJson = json.loads(data)
            results = dataJson['results']
            print(results)

例4
对于多个文件的读写,可以写成以下两种方式:
4.1

with open('C:\Desktop\text.txt','r') as f:
    with open('C:\Desktop\text1.txt','r') as f1:
        with open('C:\Desktop\text2.txt','r') as f2      
        ........       
        ........       
        ........

4.2

with open(''C:\Desktop\text.txt','r') as f:
........
with open(''C:\Desktop\text1.txt','r') as f1:
........
with open('C:\Desktop\text2.txt','r') as f2:
........

前面讲的默认都是读取文本文件,并且是UTF-8编码的文本文件。要读取二进制文件,比如图片、视频等等,用’rb’模式打开文件即可

写文件

写文件和读文件是一样的,唯一区别是调用open()函数时,传入标识符’w’或者’wb’表示写文本文件或写二进制文件,a表示在文件末尾写入:

例1

with open('E:\python\python\test.txt', 'w', encoding='gbk') as f:
    f.write('Hello, python!')
    f.write("\n")  # with自带文件关闭功能,不需要再写f.close()

要写入特定编码的文本文件,请给open()函数传入encoding参数,将字符串自动转换成指定编码

例2

import json

# 1 json->string
student = {"id": "123", "name": "122", "age": 18}
print(type(student))  # <class 'dict'>
print(student)  # {'id': '123', 'name': '122', 'age': 18}

with open('test.json', 'a', encoding='utf-8') as f:
    s = json.dumps(student, ensure_ascii=False)  # 中文不乱码
    print("s:", s)
    f.write(s)
    f.write("\n")  # with自带文件关闭功能,不需要再写f.close()
    f.write(s)
    f.write("\n")  # with自带文件关闭功能,不需要再写f.close()

输出文件
test.json

{"id": "123", "name": "122", "age": 18}
{"id": "123", "name": "122", "age": 18}

例3

r_json = [
    {"id": "123", "name": "122", "age": 18},
    {"id": "222", "name": "122", "age": 18}
]
with open('./out2.json', 'w', encoding='utf-8') as out_file:
    json.dump(r_json, out_file, ensure_ascii=False)

输出

out2.json

[{"id": "123", "name": "122", "age": 18}, {"id": "222", "name": "122", "age": 18}]

例4

import json

result = list()
student = {"id": "123", "name": "122", "age": 18}
result.append(student)
result.append(student)

with open('./out.json', 'w', encoding='utf-8') as out_file:
    json.dump(result, out_file, ensure_ascii=False)

输出文件

out.json

[{"id": "123", "name": "122", "age": 18}, {"id": "123", "name": "122", "age": 18}]

例5

error_list = list()
error_list.append('111')
error_list.append("222")

with open('./out_todo.txt', 'w', encoding='utf-8') as out_file:
    out_file.writelines('\n'.join(error_list))

输出文件

out_todo.txt

111
222
作者:admin  创建时间:2023-05-29 17:04
最后编辑:海马  更新时间:2024-11-02 21:53