txt数据文件的读写操作

一、数据的读取
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()
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值