pythonlistfilefile-processing

Python: how to get each element in a str list and then put the first element into the first file in a directory, second element in the second dir?


I'm trying to deal with txt files.

I have a 2D list called reps = [], len(reps) = 41, I also have a directory called replies, which contains 34 txt files.

I want to do like this:

how can I achieve this?

I would be very appreciate


Solution

  • reps = ...
    for i, lst in enumerate(reps, start=1):
        with open(f"replies/file{i}.txt", "w") as f:
            f.writelines(line + '\n' for line in lst)
    

    Although if you indeed have 41 lists of strings in reps, this will result in 41 files, not 34:

    replies/file1.txt
    replies/file2.txt
    ...
    replies/file41.txt
    

    If I misunderstood you and you actually really want to just replace exactly 34 files that already exist in that directory, you can always just add a conditional break in the beginning of the loop:

    ...
    for i, lst in enumerate(reps, start=1):
        if i > 34:
            break
        ...
    

    Note that writelines expects each element in the provided iterable to provide its own line seperator, which is why the generator produces line + '\n' for every line.