I have a text file with a string like 0.0.1 and I want to remove the decimals to make it 001 or just 1. So for example a 1.0.1 would become a 101.
I thought about using the round() but it would turn 0.0.1 into 0 and that's not what I want.
Use replace()
Try something like this code block:
new_file = open('newfile.txt','w')
line_file = open('myfile.txt','r').readlines()
for line_in in line_file:
line_out = line_in.replace('.','')
new_file.write(line_out)
That should read your file, remove all the periods, and write the result to a new file.
If it doesn't work for your specific case, comment on this answer and I'll update the codeblock to do what you need.
p.s. As per the comment below, you could make this happen in one line with:
open('newfile.txt','w').write(open('myfile.txt','r').read().replace('.',''))
So use that if you want to.
readlines() as it makes the file easier to iterate through as a list of strings. As part of the list making process, it does strip the newline character. it could be done as new_file.write(open('myfile.txt'.'r').read().replace(',','')) but that isn't readable for someone new to the concept.with open("myfile.txt") as f:for line in f:..., using read or readlines reads the whole file into memory which is not always possiblewith to open and iterating over the file object would be the pythonic way to do it, you are still adding blanks lines in between adding another newline in your first example, readlines does not strip.
replace()function to replace all of the periods with an empty string. The implementation isnew = old.replace('.','')