一、数据的读取
1、
open()函数打开文件
read()函数读取文件中的所有内容
lsm=open('a.txt',mode='r') #r指读入,w指写入
content=lsm.read()
lsm.close()#关闭文件,否则文件会一直被python占用,不能被其他进程使用
2、在操作后自动关闭文件
with open('a.txt') as f:
content=f.read()
print(content)
3、指定读取的字符数
lsm=open('a.txt',mode='r')
content=lsm.read(5)
lsm.close()
二、数据的写入
lsm=open('a.txt',mode='w')
content=lsm.write('hello.world!')
lsm.close()
三、文本文件的操作
txt文件或csv(逗号分隔值文件格式)
1、readline()每次读入一行数据
2、readlines()一次性读入所有数据
(1)将读入的每行数据存储为一个字符串,仍包含换行符,得到由每行字符串组成的列表。
(windows系统的换行符是\r\n,linux系统的换行符号是\n)
(2)strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符,\r\n\t)或字符序列。
注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
(3)对读入的数据使用for循环对每一个元素(每行字符串)去除换行符,并以\t的形式对字符串进行分割,返回一个列表
lsm=open('a.txt',mode='r')
content=lsm.readlines()
lsm.close()
new_content=[]
for word in content:
tmp=word.strip()
tmp=tmp.split('\t')
new_content.append(tmp)
print(new_content[0])#返回第一行内容分割后的列表
print(new_content[1])#返回第二行内容分割后的列表
>>>['wang','lulu','#']
>>>['hu','bu','li']
3、write()逐次写入文件,writelines()将列表里的数据一次性写入
4、写入文件时,join()方法将每个变量数据以\t的形式合成一个字符串,需要换行时,在每条数据后面加换行符\n
lsm=open('a.txt',mode='w')
content=[['wang','lulu','#'],['hu','bu','li']]
for word in content:
word='\t'.join(word)
word=con+'\r\n'#\n
lsm.write(word)
lsm.close()
>>>
wang lulu #
hu bu li
5、csv文件
(1)读取
import csv
path= "data/samename.csv"
lsm=open(path,'r',encoding='utf-8',errors='ignore')#utf-8避免出现gbk不能解码文件字符的问题
reader=csv.reader(lsm)
content=list(reader)
lsm.close()
print(reader)
print(content[0])
>>><_csv.reader object at 0x000001EC984D5D48>
>>>['id\tname\tSim_basic\tSim_research\tSim_experience\tsame_number']
(2)写入
path1= "data/write_samename.csv"
lsm1=open(path1,'w',encoding='utf-8',errors='ignore')
writer=csv.writer(lsm1)
writer.writerows(content)
lsm1.close()