Hello,

the task is to mix lines in text files with the same name in different folders, for example c: \ Users \ i \ 200818comments.txt where i = 1 ... n

import random for i in range(1, 10): filename = 'c:\\Users\\i\\200818comments.txt' f = open(filename) lines = f.readlines() f.close() random.shuffle(lines) f = open(filename,'w') f.writelines(lines) f.close() 

Unfortunately, this approach does not work: [Errno 2] No such file or directory Please tell me how to solve the issue

    1 answer 1

    Of course it does not work. Here in this line

    filename = 'c:\\Users\\i\\200818comments.txt'

    it's not enough to just write i inside a string, you need to explain to python that it should replace it with the value of the corresponding variable. Use string formatting :

    filename = 'c:\\Users\\{}\\200818comments.txt'.format(i)

    And another tip: in order not to write double slashes (this can be very confusing and lead to errors), use raw lines :

    filename = r'c:\Users\{}\200818comments.txt'.format(i)

    • one
      You can: fr'c:\Users\{i}\200818comments.txt' Although the option with format is more readable in this case ( i more noticeable). - jfs