By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,589 Members | 1,194 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,589 IT Pros & Developers. It's quick & easy.

TypeError: write() argument must be str, not list while writing to file

P: 1
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
djangoAPI
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
djangoAPI
Desired Output file after 2 execution

Django 2.1:2
djangoAPI
Django 2.1:1
djangoAPI
Django 2.1:0
djangoAPI
3 Weeks Ago #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.