使用python修改文件并立即写回到原始位置操作(inplace读写)
作者:GhostFromHeaven 时间:2021-02-04 11:22:31
很多应用多需要处理文件,而处理文件有一个固定的模式:打开文件,读入一些数据,处理这些数据,打印到屏幕上或写入另一个文件。
那么,如果我们想修改之后立即写回文件,该怎么做呢?用什么模式打开?又怎么读写?
我个人尝试了很多中方法,不是无法实现,就是操作非常麻烦。最终放弃。
幸运的是,Python内置模块fileinput就可以轻松完成。代码如下:
import fileinput
for line in fileinput.input(r"D:\1.txt", inplace=1):
print line.replace('d', 'b'),
足够简单吧。(将文件中的‘d'替换成'b')。
关于更多fileinput的资料,在这里http://docs.python.org/library/fileinput.html
补充知识:python在一个字符串中找到另外一个字符串并找到该字符起始的位置
代码详解
def index_of_str(seq, sub_seq):
index=[]
n1=len(seq)
n2=len(sub_seq)
for i in range(n1-n2+1):
#print('seq==%s' % (seq[i:i + n2]))
if seq[i:i+n2]==sub_seq:
#print('seq==%s'%(seq[i:i+n2]))
index.append(i+1)
print(index)
index_of_str('ATGATAGAGGGATACGGGATAG', 'GATA')
def index_of_str(s1, s2):
global dex
dex=0
index=[]
lt=s1.split(s2)
print(lt)
num=len(lt)
for i in range(num-1):
dex+=len(lt[i])
index.append(dex)
dex+=len(s2)
print(index)
#if len(lt)==1:
#return -1
#return len(lt[0])
print(index_of_str('ATGATAGAGGGATACGGGATAG', 'GATA'))
来源:https://blog.csdn.net/GhostFromHeaven/article/details/7803901
标签:python,文件,位置,inplace
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python实现批量生成,重命名和删除word文件
2022-12-03 05:51:33
![](https://img.aspxhome.com/file/2023/0/89380_0s.png)
Python爬虫定时计划任务的几种常见方法(推荐)
2021-06-02 02:05:39
![](https://img.aspxhome.com/file/2023/2/76932_0s.png)
firefox 2正则表达式
2008-08-25 19:15:00
封装2个ajax函数
2010-09-03 18:14:00
python 内置函数filter
2023-01-07 21:53:37
python生成指定长度的随机数密码
2021-01-24 23:53:17
Python实现生成对角矩阵和对角块矩阵
2021-03-16 11:45:00
![](https://img.aspxhome.com/file/2023/5/105405_0s.png)
Python的动态重新封装的教程
2023-08-23 15:26:39
Dreamwaver 常见问答解答
2009-07-05 18:51:00
用 Django 开发一个 Python Web API的方法步骤
2021-05-24 02:36:11
PHP中的函数嵌套层数限制分析
2023-11-21 08:43:24
在opera里css出现渲染问题
2009-01-15 12:19:00
机器深度学习二分类电影的情感问题
2022-07-17 06:13:28
![](https://img.aspxhome.com/file/2023/1/72851_0s.png)
Python基于pyCUDA实现GPU加速并行计算功能入门教程
2021-11-01 08:24:58
![](https://img.aspxhome.com/file/2023/2/85332_0s.jpg)
Python数据可视化实现多种图例代码详解
2022-02-11 04:01:38
![](https://img.aspxhome.com/file/2023/5/103665_0s.jpg)
js查找父节点的简单方法
2023-09-11 01:12:42
《JavaScript语言精粹》译者序及样章试读
2009-04-03 11:38:00
Python 2种方法求某个范围内的所有素数(质数)
2022-09-07 08:43:40
![](https://img.aspxhome.com/file/2023/0/117990_0s.jpg)
VMware中Linux共享mysql数据库
2010-10-25 20:29:00
![](https://img.aspxhome.com/file/UploadPic/201010/25/20101025203556695s.jpg)
python中threading超线程用法实例分析
2023-12-14 13:05:45