python 写入文件

write writelines

with open("test.txt",'w+') as f:
    f.write("hello world!")

with open("test.txt",'w+') as f:
    f.writelines("hello world!")

以上没有区别

但是writelines 可以以列表作为参数:

with open("test.txt",'w+') as f:
    f.writelines(["hello world!","first test"])

但是"hello world!" 和 "first test" 并不会 自动换行需要自己加入换行符:

with open("test.txt",'w+') as f:
    f.writelines(["hello world!\n","first test"])

read() readline() readlines()

with open("test.txt","r+") as f:
    a_read = f.read()

with open("test.txt","r+") as f:
    b_readline = f.readline()

with open("test.txt","r+") as f:
    c_readlines = f.readlines()


print(a,b,c)

a_read:'hello world!\nfirst test' //read 把整个文件读取成一个字符串
b_readline:'hello world!\n' //一次读取一行作为字符串
c_readlines:['hello world!\n', 'first test'] //一次读取所有文件,一行作为列表中的一个元素

猜你喜欢

转载自www.cnblogs.com/wanderingfish/p/9335315.html