简单介绍  --- 读

1.按行读取方式readline()

readline()每次读取文件中的一行,需要使用永真表达式循环读取文件。但当文件指针移动到文件的末尾时,依然使用readline()读取文件将出现错误。因此程序中需要添加1个判断语句,判断文件指针是否移动到文件的尾部,并且通过该语句中断循环。

# -*- coding: utf-8 -*-

file =open('/Users/april_chou/Desktop/WorkSpace/Selenium/seleniumTest/test.txt','r')

context = file.read()

print('read格式:')

print(context)

file.close()

print()

输出结果:

read格式:

hello world

hello China

2.多行读取方式readlines()

使用readlines()读取文件,需要通过循环访问readlines()返回列表中的元素。函数readlines()可一次性读取文件中多行数据。

实例1:

file =open('C:/Users/april_chou/Desktop/WorkSpace/Selenium/seleniumTest/test.txt','r')

context = file.readlines()

contextLines =''

for i in context:

    contextLines = contextLines + i

print('readlines格式:')

print(contextLines)

file.close()

print()

输出结果:

readlines格式:

hello world

hello China

实例二:

file =open('C:/Users/april_chou/Desktop/WorkSpace/Selenium/seleniumTest/test.txt','r')

contextLines =''

while True:

    context = file.readline()

    contextLines = contextLines + context

    if len(context) ==0:

    break

print('readline格式:')

print(contextLines)

file.close()

输出结果:

readline格式:

hello world

hello China

3.一次性读取方式

read()读取文件最简单的方法是使用read(),read()将从文件中一次性读出所有内容,并赋值给1个字符串变量。

NB:要注意这个地址的问题。一定要写出准确的地址。

 

参考:https://www.cnblogs.com/April-Chou-HelloWorld/p/8833874.html

简单介绍  --- 写

写的方式很简单,基本就三行,但是要注意的是,在write的函数中,target只能是str,不可以是list或者数组等。

file_target = open("地址", 'w')  # 打开文件

file_target.write(target) #执行完所有写的操作再关闭文件

file_target.close()

如何把str转换成list ,请参考文章:https://blog.csdn.net/qq_36098284/article/details/88603127

NB:还有一件事需要注意,比如你想一条条往文件中写数据, 你就只能打开文件一次,然后执行所有写的操作,全部执行完了再关闭。如果你打开一次,写一下,关上,想写的时候再打开,写完再关上,代价就是你的txt中只有最后一次你写入的内容,上面的工作都会被覆盖掉。这点需要注意。(开始我用的时候就没有注意这一点,导致写了半天,啥也没 写出来)