014、文件的读取、写入

 

文件的读取、写入

  参考资料:https://www.cnblogs.com/zyber/p/9578240.html

         https://www.runoob.com/python3/python3-file-methods.html

1、open函数

  a、open('test.txt', mode='r', encoding='utf-8') 

  b、第一个参数:要打开的文件,同级目录下('test.txt) ;

  c、第二个参数 mode 以何种方式打开,r是 只读,w 是只写 ;

  d、第三个参数 encoding 表示以何种编码的方式打开文件要和 (test.txt) 文件的编码保持一致;

    对 test.txt 文件 以某种编码write()后,在read()时也要以同样的方式读取 ;

  e、f = open('test.txt', mode='w', encoding='utf-8')    # 执行完这一段代码后,test.txt文件内容 在打开的时候清掉 ;

  f、使用 open() 方法一定要保证关闭文件对象,即调用 close() 方法  。

            文件属于非python的第三方资源(txt、excel、数据库),用完之后要close() ;

    可以使用  with  open()  as f :  

 

2、读、写操作

  read()  :读取所有数据,读取出来为字符串 ;

  readline(): 读取一行

    readlines  :读取所有行数据。结果为列表,一行为一个成员 ; 

    write(字符串): 传的参数是字符串;如果传入int会报错;

    writelines(列表) :传的参数是列表;

  文件写入数据时,不会自动换行,需要在字符串中拼接 \n  ;

 

  怎么查看 test.txt 文件的编码格式呢? 用note pad++,如下,表示文件使用的是 ansi 编码 :

  

 

  示例代码如下:

# test_aa.txt的编码格式是 utf-8,参数encoding='utf-8' ,正常执行;
f = open('test_aa.txt', mode='r', encoding='utf-8')
print(f.read())

# test.txt的编码格式是 ansi,参数encoding='utf-8' ,在执行的时候会报错;
f = open('test.txt', mode='r', encoding='utf-8')
print(f.read())
View Code

  执行结果如下:

D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day06\venv\Scripts\python.exe D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day06/hh/test_02.py
Traceback (most recent call last):
  File "D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day06/hh/test_02.py", line 46, in <module>
    print(f.read())
  File "C:\SkyWorkSpace\WorkTools\python\Python38\lib\codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd5 in position 0: invalid continuation byte
账号    密码
客定     12345
克文     23456

Process finished with exit code 1
View Code

 

 Python引入了  with语句  来自动帮我们调用  close()方法

with open('des.conf', 'a') as f:
    f.write('Hello, world!')

  示例代码如下:同级目录下有个 des.conf 文件

# 读取文件 r
# Python引入了with语句来自动帮我们调用close()方法:

with open('des.conf', 'r') as f:
    print(f.read())

# 写入文件,a 表示以追加的方法写入
with open('des.conf', 'a') as f:
    f.write('Hello, world!')

# 读取文件 r
with open('des.conf', 'r') as f:
    print(f.read())
View Code

  执行结果如下:

D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day06\venv\Scripts\python.exe D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day06/hh/test_02.py
Hello, world!
Hello, world!Hello, world!

Process finished with exit code 0
View Code

 

 f.write( )  、 f.writelines( ) 所有的写入操作,并不是单个写入,而是一次性写入。

# 执行完下面3个write语句后,才一次性把字符写入到本地stu_info.txt
# 并不是,先写入“代码写入中文txt111” 再写入 “代码写入中文txt222”
# 写入时,需要自己加换行符
with open('stu_info.txt', 'a') as f:
    f.write('代码写入中文txt111')
    f.write('\n代码写入中文txt222')
    f.write('\n代码写入中文txt333')


stu_info = ['sky', 'jack', 'tony']
stu_info_1 = ['克定', '克强', '克文']
with open('stu_info_1.txt', 'a') as f:
    f.writelines(stu_info)
    f.writelines('\n')
    f.writelines(stu_info_1)
View Code

 

 

 

  综合整理代码如下:

print('========= read() 方式读取 ============')
f = open('test.txt', mode='r', encoding='utf-8')
print(f.read(4))        # 类似于位置指针,读取前4个;
print(f.read())         # 然后跟着指针读取完所有的

print('========= readlines() 方式读取 ============')

f = open('test.txt', mode='r', encoding='utf-8')
print(f.readline())        # 读取一行
print(f.readlines())       # 读取所有行


# Python引入了 with语句 来自动帮我们调用 close()方法:
print('============with语句 来自动帮我们调用 close()方法:=============')
# 写入文件,a 表示以追加
# 在此处以 encoding='utf-8' ,在其他地方读取该文件时,需以同样的编码 utf-8
with open('test.txt', 'a', encoding='utf-8') as f:
    f.write('\n写入操作')

print('=========================')
# 读取文件,r 表示只读
with open('test.txt', 'r', encoding='utf-8') as f:
    print(f.read())
View Code

  执行结果如下:

D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day06\venv\Scripts\python.exe D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day06/hh/test_02.py
========= read() 方式读取 ============
账号密码

客定12345
克文23456
写入操作
写入操作
========= readlines() 方式读取 ============
账号密码

['客定12345\n', '克文23456\n', '写入操作\n', '写入操作']
============with语句 来自动帮我们调用 close()方法:=============
=========================
账号密码
客定12345
克文23456
写入操作
写入操作
写入操作

Process finished with exit code 0
View Code

 

 

练习:

  把 下面的 列表数据 写入到 stu_info.txt ,  然后再从 stu_info.txt  读取出来;

stu_info = [{'name': '克定', 'age': 25, 'weight': 65, 'height': 175, 'hobby': '游泳'},
            {'name': '克文', 'age': 20, 'weight': 75, 'height': 170, 'hobby': '打球'},
            {'name': '克强', 'age': 23, 'weight': 55, 'height': 171, 'hobby': '跑步'},
            {'name': '世凯', 'age': 50, 'weight': 55, 'height': 180, 'hobby': '打仗'}
            ]

  代码如下:

stu_info = [{'name': '克定', 'age': 25, 'weight': 65, 'height': 175, 'hobby': '游泳'},
            {'name': '克文', 'age': 20, 'weight': 75, 'height': 170, 'hobby': '打球'},
            {'name': '克强', 'age': 23, 'weight': 55, 'height': 171, 'hobby': '跑步'},
            {'name': '世凯', 'age': 50, 'weight': 55, 'height': 180, 'hobby': '打仗'}
            ]

print('写入txt前的原始列表数据:{0}'.format(stu_info))
# 把列表数据写入到 stu_info.txt
with open('stu_info.txt', mode='w', encoding='utf-8') as f:
    keys = stu_info[0].keys()
    f.write(','.join(keys))

    for i in stu_info:
        temp = []
        for j in keys:
            temp.append(str(i[j]))
        res = ','.join(temp)
        f.write('\n')
        f.write(res)


# 从 stu_info.txt 读取数据
with open('stu_info.txt', mode='r', encoding='utf-8') as f:
    all_lines = f.readlines()
    new_list = []
    # print(all_lines)
    for i in all_lines:
        res = i.strip('\n')
        # print(res)
        temp_list = res.split(',')
        # print(temp_list)
        new_list.append(temp_list)

    # print(new_list)

    # 从列表取值,给到字典,最后组合成列表
    result_list = []
    for i in range(1, len(new_list)):
        stu_info_2 = {}
        for j in range(len(new_list[0])):
            if new_list[i][j].isdigit():
                stu_info_2[new_list[0][j]] = int(new_list[i][j])
            else:
                stu_info_2[new_list[0][j]] = new_list[i][j]

        result_list.append(stu_info_2)

print('从txt读取到的数据:{0}'.format(result_list))
View Code

  执行结果如下:

D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day09\venv\Scripts\python.exe D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day09/test_02/test_a.py
写入txt的原始列表数据:[{'name': '克定', 'age': 25, 'weight': 65, 'height': 175, 'hobby': '游泳'}, {'name': '克文', 'age': 20, 'weight': 75, 'height': 170, 'hobby': '打球'}, {'name': '克强', 'age': 23, 'weight': 55, 'height': 171, 'hobby': '跑步'}, {'name': '世凯', 'age': 50, 'weight': 55, 'height': 180, 'hobby': '打仗'}]
从txt读取到的数据:[{'name': '克定', 'age': 25, 'weight': 65, 'height': 175, 'hobby': '游泳'}, {'name': '克文', 'age': 20, 'weight': 75, 'height': 170, 'hobby': '打球'}, {'name': '克强', 'age': 23, 'weight': 55, 'height': 171, 'hobby': '跑步'}, {'name': '世凯', 'age': 50, 'weight': 55, 'height': 180, 'hobby': '打仗'}]

Process finished with exit code 0
View Code

 

 

 

 

 

注意:用代码的方式把中文写入到 conf 文件,conf文件在pycharm中显示带问号,双击打不开该文件。

参考连接:  https://www.cnblogs.com/qq-2780619724/p/15073331.html

posted @ 2021-07-28 12:04  空-山-新-雨  阅读(406)  评论(0编辑  收藏  举报