读写txt文件

1、将内容写入txt文件
1 def txt(cont, path):
2     for i in cont:
3         with open(path, "a") as f:
4             # s = str(item[i]).replace('[', '').replace(']', '') + '\n'  # i为列表时
5             # f.write(str(i))
6             f.write(str(i) + ',')  # 自带文件关闭功能,不需要再写f.close
注:cont为要写入txt的内容, path为txt文件路径


2、从txt文件读取内容
 1 def read_txt(filename):
 2     txt = []
 3     try:
 4         f = open(filename)
 5         while True:  # 循环读取文本里面的内容
 6             line = f.readline()  # 一行一行的读
 7             if not line:  # 如果没有内容,则退出循环
 8                 break
 9             # line = float(line.strip("\n")) line内有换行符时
10             txt.append(line)
11     except Exception as e:
12         pass

注:filename为txt文件路径。

 

 

 

posted @ 2021-08-13 16:46  编程大白77  阅读(601)  评论(0)    收藏  举报