Python 替换.txt文件中的字符

2023年4月29日09:09:15

需求.txt文件中存在空格,将其每个数字后面加上一个“,”

要处理的文件格式:此时每行后面已加入“,”,使用的方法:在notepad++中替换,将"$"替换为",",选择正则表达式,全部替换,此时每行数字后面都有“,”。但每行数字之间不存在“,”,使用替换命令,参考后面代码。

源.txt

4    4,
4    4,
-4    -4,
5    5,
1    1,
11    11,
5    5,
9    9,
3    3,
7    7,
-11    -11,
11    11,
54    54,
275    275,
324    324,
-354    -354,

目的效果类似于.txt

0, 0,
0, 0,
2, 2,
0, 0,
0, 0,
-1, -1,
0, 0,
0, 0,
-1, -1,
0, 0,
-1, -1,
1, 1,
0, 0,
0, 0,
-1, -1,

python代码:

#encoding=utf-8
import re
import os
import sys
 
file_open=open(sys.argv[1])

filewritepath=os.path.dirname(sys.argv[1])+"\\Result.txt"

file_write=open(filewritepath,'w')
 
listfile=file_open.read()
listf=re.split('[ \n\r]',listfile)
i=0
 
while i<len(listf)-2:
	listt=listf[i].replace("\t",", ");
	file_write.write(listt);
	i=i+1;
	file_write.write("\n");
 
file_open.close()
file_write.close()
print "Finish "
print filewritepath

使用方法:打开cmd,输入python,拖入此文件和要处理的txt,生成对应:文件Result.txt。。

  • 作者:will-well
  • 原文链接:https://blog.csdn.net/yanhuatangtang/article/details/93327706
    更新时间:2023年4月29日09:09:15 ,共 797 字。