zl程序教程

您现在的位置是:首页 >  后端

当前栏目

软件测试|一文教你学会Python文件 I/O 操作

Python文件 操作 学会 软件测试 文教
2023-06-13 09:17:13 时间

Python文件I/O操作

文件的创建于写入读取操作是我们学习一门语言的必会操作,Python也提供了很方便的文件创建和读写操作,本篇文章我们就将向大家介绍这些操作。

文件创建与写入

  • 功能:生成文件对象,进行创建,读写操作
  • 用法:open(path,mode)
  • 参数说明:
    • path:文件路径
  • mode:操作模式
  • 返回值
    • 文件对象

语法如下:

f = open('test.txt', 'w')

参数分类:

参数

介绍

w

创建文件

w+

创建文件并读取

wb

二进制模式创建文件

wb+

二进制模式创建或增加内容

文件对象常用操作方法:

方法名

参数

介绍

write

message

写入内容

writelines

message_list

批量写入

close

关闭并保存文件

上述各方法代码如下:

# 写入文件
def fun_1():
    f = open('hello.txt','w')

    f.write('Hello World')

    f.write('Good Morning')

    f.close()

# 写入换行
def fun_2():
    f = open('hello2.txt', 'w')

    f.write('Hello World\n')

    f.write('Good Morning\n')

    f.close()

# 写入列表
def fun_3():
    f = open('hello3.txt', 'w')

    text_lines = ['Hello World\n','Good Morning\n']

    f.writelines(text_lines)

    f.close()

# 追加文件
def fun_4():
    f = open('hello2.txt','a')

    f.write('The end\n')

    f.close()



if __name__ == "__main__":
    print("hello python~")
    fun_1()
    fun_2()
    fun_3()
    fun_4()

文件读取

读取模式介绍

参数

介绍

r

读取文件

rb

二进制模式读取文件

操作参数介绍

方法名

参数

介绍

read

返回整个文件内容字符串

readlines

返回文件列表

readline

返回文件中的一行

示例代码如下:

# 读取文件 read
def fun_5():
    f = open('hello2.txt', 'r')

    text = f.read()

    print('text:\n',text)

# 读取文件 readlines
def fun_6():
    f = open('hello2.txt','r')

    print(f.readlines())

# with与open
def fun_7():
    with open('hello7.txt','w') as f:
        f.write('Hello world\n')
        f.write('Good Morning\n')
if __name__ == "__main__":
	fun_5()
    fun_6()
    fun_7()
-----------------------------
输出结果如下:
text:
 Hello World
Good Morning
The end

Yaml文件的读取

yaml文件我们经常使用的标记语言,支持多语言,读写方便,我们在自动化测试的参数化中经常使用到yaml文件,所以这里我们重点介绍一下yaml的读取。

Python的第三方模块-PyYaml

  • pip install PyYaml
  • import yaml

yaml文件的读取

f = open(yaml_file, 'r')
data = yaml.load(f.read())
f.close

返回值(字典类型):

{
    'name':'muller',
    'age':34,
    'xinqing':['haha','heihei']
}

总结

本文主要介绍了Python文件的I/O操作,我们介绍了创建文件,写入内容,读取文件内容的操作,并且介绍了读取yaml文件的内容,后续我们会讲解其他关于Python的内容。