[英]editing a single element in text file in python
我有 500 個 *.txt 文件,格式如下
1 0.211648 0.496528 0.230114 0.159722
11 0.549716 0.232639 0.082386 0.145833
5 0.687500 0.539931 0.130682 0.128472
1 0.534091 0.809028 0.221591 0.194444
2 0.127841 0.637153 0.119318 0.128472
2 0.579545 0.482639 0.090909 0.069444
1 0.657670 0.269097 0.105114 0.121528
2 0.737216 0.348958 0.025568 0.086806
2 0.484375 0.302083 0.031250 0.069444
我需要用'10'替換行中的'11'第一個數字我已經為它編寫了以下程序,但它不起作用。 你能幫忙嗎?
import numpy as np
import glob
import os
os.chdir(r'../images')
myFiles = glob.glob('image*.txt')
import numpy as np
for i1 in myFiles:
# print(i1)
with open(i1, 'r') as f:
# read a list of lines into data
lines = f.readlines()
r_id = np.arange(len(lines))
for i in r_id:
idx = list(map(float, lines[i].split(' ')))
idx[0]=int(idx[0])
if(idx[0]==11):
idx[0]=10
with open(i1, 'w') as f:
f.writelines(lines)
f.close()
您正在嘗試使用整數(10 和 11),但您所擁有的是字符串。 您不需要 numpy ,這是一個簡單的文本替換:
import glob
import os
os.chdir('../images')
myFiles = glob.glob('image*.txt')
for i1 in myFiles:
lines = open(il,'r').readlines()
with open(il,'w') as fout:
for line in lines:
if line.startswith('11 '):
line = '10 '+line[3:]
print( line, file=fout, end='' )
如果您想將結果寫入臨時文件並隨后重命名,它可能會更簡單。 那么你就不需要讀入整個文件了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.