Вы можете перебирать строки с lines = filedata.split("\n")
. Будьте осторожны, потому что filedata
- это большая строка, содержащая весь файл. Когда вы сделали for line in filedata
, вы перебрали все символы в файле ...
Я также использовал другой способ (без regex
), чтобы найти числа и изменить их.
def edit(file):
with open(file, "r") as f:
filedata = f.read()
lines = filedata.split("\n") # list of lines
for index, line in enumerate(lines):
if "keyword" in line:
words = line.split() # ['keyword', '1.50', '1.63', '1.56', '1.45']
for i, w in enumerate(words):
try:
# transform number to float, multiply by 10000
# then transform to integer, then back to string
new_word = str(int(float(w)*10000))
words[i] = new_word
except:
pass
lines[index] = " ".join(words)
new_data = "\n".join(lines) # store new data to overwrite file
with open(file, "w") as f: # open file with write permission
f.write(new_data) # overwrite the file with our modified data
edit("myfile.txt")
Вывод:
# myfile.txt
abcdef 178 211 208 220
ghijkl 0 0 0 0
keyword 15000 16299 15600 14500
РЕДАКТИРОВАТЬ : более компактный способ
def edit(file):
with open(file, "r") as f:
filedata = f.read()
line = [x for x in filedata.split("\n") if "keyword" in x][0]
new_line = line
for word in line.split():
try: new_line = new_line.replace(word, str(int(float(word)*10000)))
except: pass
with open(file, "w") as f: # open file with write permission
f.write(filedata.replace(line, new_line)) # overwrite the file with our modified data
edit("myfile.txt")