how Python for loop variable(K) in range(1,11) is used in a word like HHkC and show HH1C,HH2C......HH10C?

Viewed 148

I ran a for loop for range(1,11) and used k as a variable. but K in HHk_C.txt or HHkC is not interpreted as HH1_C.txt or HH1C rather python read this as HHk_C.txt and HHkC. how can I tell python to read HHk_C.txt or HHkC as HH1_C.txt or HH1C (1 to 10) ?

CODE

for k in range(1,11):
with open('HHk_C.txt') as f:
    HHkC = f.read().splitlines()
with open('HHk_M.txt') as f:
    HHkM = f.read().splitlines()
with open('HHk_W.txt') as f:
    HHkW = f.read().splitlines()
x[k] = Function(HHkC,HHkM)
y[k] = Function(HHkC,HHkW)

ERROR

---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-9-4574aac9a0b3> in <module>()
      1 for k in range(1,11):
----> 2     with open('HHk_C.txt') as f:
      3         HHkC = f.read().splitlines()
      4     with open('HHk_M.txt') as f:
      5         HHkM = f.read().splitlines()

IOError: [Errno 2] No such file or directory: 'HHk_C.txt'
1 Answers

You can use f-strings

for i in range(1, 11):
    with open(f'HH{i}_C.txt') as f:
        #do something
Related