python文件读写方法

171 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第6天,点击查看活动详情


大家好,我是芒果,一名非科班的在校大学生。对C/C++、数据结构、Linux及MySql、算法等领域感兴趣,喜欢将所学知识写成博客记录下来。 希望该文章对你有所帮助!如果有错误请大佬们指正!共同学习交流

作者简介:



读文件

read: 读指定长度字节数的数据, 返回一个字符串.

a = open('Z:/test.txt','r')
print(a.read())
#执行结果:
hello world
hello python

readline: 读取一行数据, 返回一个字符串

a = open('Z:/test.txt','r')
print(a.readline())  #hello world

readlines: 读取整个文件, 返回一个列表. 列表中的每一项是一个字符串, 代表了一行的内容

a = open('Z:/test.txt','r')
print(a.readlines())    #['hello world\n', 'hello python']

直接使用for line in f的方式循环遍历每一行, 功能和readline类似. 一次只读一行,

相比于readlines占用内存少, 但是访问IO设备的次数会增多, 速度较慢

a = open('Z:/test.txt','r')
for line in a:
    print(line)
#执行结果:
hello world
​
hello python

注意, readline或者readlines这些函数仍然会保留换行符. 所以我们往往需要写这样的代码来去掉换行符.

a = open('Z:/test.txt','r')
# for line in f 的方式循环遍历每一行, 功能和readline类似,返回的line是字符串,所以可以使用字符串的成员函数
for line in a:  
    print(line.strip())
#执行结果:
hello world
hello python
​
​
#或者:使用列表解析语法
a = open('Z:/test.txt','r')
data = [line.strip() for line in a.readlines()]
print(data) #['hello world', 'hello python']

readlines和for line in f: 的区别:

第一种方法是全部读取->只读取一次 时间快,但是占空间。第二种方式是隔行读取 ->读取多次,时间慢,但是省空间。读取大文件选方式2


写文件

write: 向文件中写一段字符串

  • 如需写文件, 必须要按照 'w' 或者 'a' 的方式打开文件. 否则会写失败.
a = open('Z:/test.txt','r')
a.write("hello Mango")  #io.UnsupportedOperation: not writable

a = open('Z:/test.txt','w')
a.write("hello Mango")  #用w方式打开,原文件的内容被删除

image-20220320144757014


a = open('Z:/test.txt','a')
a.write("hello Lemon")  #以a的方式打开->追加

image-20220320144851497

writelines: 参数是一个列表, 列表中的每一个元素是一个字符串.

a = open('Z:/test.txt','w')
w = ['Mango\n','hello\n',' world\n']
a.writelines(w)#把列表的内容写入到文件中

image-20220320145231050

并没有一个 writeline 这样的函数. 因为这个动作等价于 write 时在字符串后面加上 '\n'. 同理, 使用 writelines的时候, 也需要保证每一个元素的末尾, 都带有 '\n'