Reputation: 11
I have a input file like below and i am reading the file and checking the length of the file and below and want to check if arg_list[3] is null or empty and then pass '' as value to arg_list[3].
1|2|3| |5
The code is below:
f=open(input,'r')
for line in f:
arg_list=line.split('|')
if len(arg_list) == 5:
a=(arg_list[0].strip())
b=(arg_list[1].strip())
c=(arg_list[2].strip())
d=(arg_list[3].strip())
e=(arg_list[4].strip())
w=open(output,'w')
c.write("arg1=%s\n" % (a))
c.write("arg2=%s\n" % (b))
c.write("arg3=%s\n" % (c))
c.write("arg4=%s\n" % (d))
c.write("arg5=%s\n" % (e))
f.close()
expected output (output) is as below
arg1=1
arg2=2
arg3=3
arg4=''
arg5=5
Any ideas are appreciated
Upvotes: 0
Views: 155
Reputation: 195553
You can use {!r}
in str.format
to obtain your result:
If a1.txt
contains:
1|2|3| |5
then:
with open('a1.txt', 'r') as f_in, open('a2.txt', 'w') as f_out:
for line in f_in:
if line.strip() == '':
continue
s = map(lambda x: '' if x.strip()=='' else int(x), s.split('|'))
for i, v in enumerate(s, 1):
print('arg{}={!r}'.format(i, v), file=f_out)
creates a2.txt
with content:
arg1=1
arg2=2
arg3=3
arg4=''
arg5=5
Upvotes: 1