python 读与写文本

python 读取文本:

方法1:

with open(txt_path, "r") as fr:
    lines = fr.readlines()
for line in lines:
    line = line.strip() #去除换行符 \n

方法2:

f = open("tmp2.txt", "r")
line1 = f.readline()  ##一行行读取
line2 = f.readline()

f = open("tmp2.txt", "r")
lines = f.readlines() #一次性读取全部,list存放

f.close()

python 写文本

方法1:

txt_path = "./tmp.txt"
with open(txt_path, "w") as fw:
    str_1 = "hello world\n"
    fw.write(str_1)
    str_2 = "ni hao\n"
    fw.write(str_2)

很长时间内我都用这种方式来写文本,但是这种可以自动关闭文本避免内存泄露,但是就是用with open需要考虑缩进,比如在需要读取文本的地方对读取的文本进行修改再写入,读和写混在一起,这样导致缩进比较麻烦。

所以下面这种方便:

方法2:

txt_path2 = "./tmp2.txt"
f1 = open(txt_path2, "w")
str_1 = "hello world\n"
str_2 = "ni hao\n"
f1.write(str_1)
f1.write(str_2)
f1.close()

附加各种文本读写模式

posted @ 2023-01-10 10:23  无左无右  阅读(105)  评论(0编辑  收藏  举报