1 txt文件读写
1.1 txt文件读取
1.1.1 open函数读取
f = open(filename, mode='r', encoding=None, newline='')
content=f.read()
f.close()
mode常用参数:
r--只读方式打开文件,默认模式;
w--打开一个文件用于写入,存在则覆盖,不存在则创建;
a--打开一个文件用于追加,存在则写入结尾,不存在则创建。
使用open函数进行文件读写,必须close进行关闭。
如果用Windows自带的文件路径,路径引用写r"filename",可以避免\n等问题。
1.1.2 with open函数读取
with open(fileName, mode='r', encoding=None, newline='') as f:
f.read()
with open会自动调用close函数。
1.1.3 for循环读取每一行
with open(fileName, 'r') as f:
for line_t in f:
print(line_t)
此时,可能会出现很多空白行,用rstrip函数去除。
即,print(line_t.rstrip())
1.1.4 read函数读取,储存为字符串
with open(‘test.txt') as f:
txt = f.read()
1.1.5 readlines函数读取,储存为列表
# 让readlines函数储存的列表正常打印
with open('test.txt') as f:
txt = f.readlines() #txt类型是list
for line_t in txt:
print(line_t.strip())
1.2 txt文件写入
1.2.1 open函数写入
f = open(file_name, mode='w')
f.write(strTxt)
f.close()
#数值类型文件
data = 1223
f.write(str(data))
如果文件存在,w模式写入文件会清空该文件。
1.2.2 写入多行数据
多行搁一行
file_name = '1.txt'
f = open(file_name,'w')
f.write('065,Mike,Jerry,86,91,95')
f.write('070,Ja