使用python读写txt文件

1. 前言

数据分析的时候,经常需要把运行时候的过程数据保留下来,txt是最常用的保存方式,怎么样用python读写txt文本呢。

2. 方法

2.1 读

f = open("test.txt", "r")
for line in f.readlines():
    line = line.strip('\n')
    print(line)
f.close()

2.2 写

with open("test.txt", "a") as file:
    for i in range(1, 10):
        file.write(str(i) + "\n")

2.3 关键参数

在 with open("test.txt", "a") as file:  这句话中,最关键的参数在于后面的小字母“a”,使用不同的字母可以实现不同的读写模式,具体字母对应的模式,如图所示:

3. 总结

 txt读写几乎不用任何库,十分简单,关键在于选择合适的读写模式,小伙伴们可以根据自己需求选择模式。

猜你喜欢

转载自blog.csdn.net/weixin_52514564/article/details/129371645