Wessowang :
I want to find and replace floats with integers in several text files.
There is one float value per text file which I want to convert. It is always after a specific keyword and has to be multiplied by 10.000.
e.g. the float 1.5 should be turned into the integer 15.000
The other floats after 1.5 don't have to be changed though
def edit(file):
with open(file, 'r') as f:
filedata = f.read()
for line in filedata:
if "keyword" in line:
filedata = filedata.replace(re.search(r"\d+\.\d+", line).group(), str(10000*re.search(r"\d+\.\d+", line).group()))
with open(file, 'w') as f:
f.write(filedata)
I was trying to replace the the float using a regex. But this doesn't work
EXAMPLE FILE EXTRACT
abcdef 178 211 208 220
ghijkl 0 0 0 0
keyword 1.50 1.63 1.56 1.45
phoenixo :
You can iterate over lines with lines = filedata.split("\n")
. Be careful because filedata
is a big string containing the whole file. When you did for line in filedata
, you iterated over every character of the file...
I also used another way (without regex
) to find numbers and change them.
def edit(file):
f = open(file, "r")
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
f.close()
# open file with write permission
f = open(file, "w")
# overwrite the file with our modified data
f.write(new_data)
f.close()
edit("myfile.txt")
Output :
# myfile.txt
abcdef 178 211 208 220
ghijkl 0 0 0 0
keyword 15000 16299 15600 14500