Home > OS >  Python: how to get each element in a str list and then put the first element into the first file in
Python: how to get each element in a str list and then put the first element into the first file in

Time:08-26

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:

  • reps[0][0] is the first line of the file1.txt under the replies directory, reps[0][1] is the second line etc.
  • reps[1][0] is the first line of the second file2.txt
  • Until all 34 txt files have been replaced then it's done

how can I achieve this?

I would be very appreciate

CodePudding user response:

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

CodePudding user response:

You will need something like this:

from pathlib import Path
for lines, _file in zip(reps, Path("/path/to/replies/dir").iterdir()):
    with open(_file, "w") as fp:
        fp.writelines(lines)
  • Related