网络编程
位置:首页>> 网络编程>> Python编程>> python实现逐个读取txt字符并修改

python实现逐个读取txt字符并修改

作者:nudt_qxx  发布时间:2021-03-11 21:25:53 

标签:python,txt,字符

最近写毕业设计遇到一个问题,就是我从一个txt文件中逐个读取字符,并修改其中的内容后存到另一个txt文件中,如下图:

python实现逐个读取txt字符并修改

字符替换规则是把所有的0转化为1,把所有的255转化为0。当然程序里面需要遍历好多次,算法复杂度相当差,但还是实现了初衷,源码如下:


import os

with open((os.path.join('test.txt')), 'r') as f:
data=f.readlines()
for line in data:
odom=line.split()
num=map(int,odom)
lst=(list(num))
Len=len(lst)

for i in range(0,Len):
if lst[i]==255:
lst[i]=0
elif lst[i]==0:
lst[i]=1
print(lst)

with open((os.path.join('test_copy.txt')), 'w') as f:
for j in range(0,Len):
f.write(str(lst[j]))
f.write(' ')

来源:https://blog.csdn.net/xiangxianghehe/article/details/50833693

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com