I wrote one program which help inrementing the digit in the file. Able to copy only first line if I am using writelines and for f.write I am getting
f.write(new_line ) if lines[0].strip().endswith(':') else f.write([new_line, *lines]) TypeError: write() argument must be str, not list
file.txt
Django 2.1:0
djangoAPI1
djangoAPI2
My Code
import re
regex = r'(?<=:)\d*$'
def incr_patch_version(fname):
with open(fname, 'r+') as f:
lines = f.readlines()
#print (lines[0])
new_line = re.sub(regex, lambda x: str(int(x.group()) + 1 if x.group().isnumeric() else 0), lines[0])
f.seek(0)
print (*lines)
f.write(new_line ) if lines[0].strip().endswith(':') else f.write([new_line, *lines])
#f.write(new_line ) if lines[0].strip().endswith(':') else f.writelines([new_line, *lines])
fname = 'file.txt'
incr_patch_version(fname)
if I am using f.write(new_line ) if lines[0].strip().endswith(':') else f.writelines([new_line, *lines]). I am getting the below output
Django 2.1:3
Django 2.1:2
Django 2.1:1
Django 2.1:0
djangoAPI1
djangoAPI2
Desired Output file after 2 execution
Django 2.1:2
djangoAPI1
djangoAPI2
Django 2.1:1
djangoAPI1
djangoAPI2
Django 2.1:0
djangoAPI1
djangoAPI2
from TypeError: write() argument must be str, not list while writing to file
No comments:
Post a Comment