python对于文件的读取和重建

这里我想把关于对各类型文件的读取方法以及对其中数据的操作,只要是我遇到的就纪录下来

一.读取

通常我会以open函数开头,以读取txt文件为例:

data = [] # I will store the data in this list.
with open(file, mode='r') as f:
    for line in f:
        line = line.replace(old='\t', new='')
        data.append(line.strip().split())

    f.close()

这是一个比较典型的例子。用open函数将文件打开,然后用 for line in f 读取文件中的每一行数据,然后我再对这每一行的数据进行操作,我这里假设每一行数据之间相差'\t'的距离,我把这些值之间的距离丢掉了,然后对新的这一行数据进行分割并包装成列表。

这里需要灵活运用对字符串的操作 replace, strip和split.

str.replace()

str.replace(old, new[, max])

就是把字符串中old对应字符变成new对应字符,这种替换次数可以用max这个可选参数来设定。例如:

str = "He is too happy to stop laughing which makes his partner feel embarrassed."

不加限制时,

str.replace('is', 'was')
 >>'He was too happy to stop laughing which makes hwas partner feel embarrassed.'

max=2 equal to default setting

str.replace('is', 'was', 2)
>>'He was too happy to stop laughing which makes hwas partner feel embarrassed.'

max=1

str.replace('is', 'was', 1)
>>'He was too happy to stop laughing which makes his partner feel embarrassed.'

str.strip()

str.strip(char) 移除首尾中的char,仅限于首尾。默认条件下移除空格或换行符 ,不能对中间的字符进行操作。

 

参考: https://www.runoob.com/python/att-string-strip.html

str.split()

str.split(str="", num=string.count(str)).

参考: https://www.runoob.com/python/att-string-split.html

讲字符串如何进行切割,以及切割成多少块。

str -- 默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。

num -- 分割次数。默认为 -1, 即分隔所有。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值