I have a text file with just numbers, as such : 75, 7, 8, 115, 72, 102, 11, 25, 80 # dr.txt
I need to input these numbers (as one group) then subtract 1 from each number in the file, then
rewrite the file with the new numbers.
I have tried the following:
path = 'dr.txt'
with open(path, "r+") as f:
for line in f.readline().splitlines():
split_line = line.split(",")
split_line = str(int(split_line) - 1)
data.append(split_line)
with open(path, 'w') as file:
for line in data:
newnumbers = ','.join(line)
file.write(newnumbers)```
but I can't seem to get it to work.
I have seen something similar on this forum but could not make sense of it to adapt it to my
particular problem.
Any guidance is greatly appreciated.
Thank you.
cogiz
Python 3.6 user
path = 'dr.txt'
data = []
with open(path, "r", encoding='utf-8') as f:
for line in f.readlines():
line = line.replace(' ', '')
line = line.replace('\n', '')
line = line.split(",")
new_line = [str(int(value) - 1) for value in line]
data.append(new_line)
with open(path, 'w') as file:
result = ''
for line in data:
newnumbers = ','.join(line)
result += newnumbers + '\n'
file.write(result)
Thank you very much for your input.
I understand better now why it wasn’t working and I will implement your
ideas as I progress further down this Python rabbit hole.
In this case I would just read, split on comma, convert to int and do math operation, go to start of file and print back into file with comma separator:
with open("dr.txt", "r+") as f:
stream = (int(num) - 1 for num in f.read().split(', '))
f.seek(0)
print(*stream, sep=", ", file=f)
f.truncate()
EDIT: added f.truncate() as pointed out by Matthew Barnett: " the file might be shorter than what’s there already, e.g. writing 99 over the top of 100 will leave you with 990 , so you need to add f.truncate() just before closing the file"
@Alvar: There’s a small oversight there. What you write to the file might be shorter than what’s there already, e.g. writing 99 over the top of 100 will leave you with 990, so you need to add f.truncate() just before closing the file.