1

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

Mehmaam
  • 573
  • 7
  • 22
DaT.
  • 25
  • 2
  • if `len(reps) = 41` but there are only 34 txt files in the directory, what should happen for the extra entries in `reps`? – Anentropic Aug 26 '22 at 10:29

2 Answers2

0
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.

Daniil Fajnberg
  • 12,753
  • 2
  • 10
  • 41
-1

You are probably looking something like this:

from pathlib import Path
for lines, file_path in zip(reps, Path("/path/to/replies/dir").iterdir()):
    with open(file_path, "w") as f:
        f.writelines([l + "\n" for l in lines])
  1. Path("/path/to/replies/dir").iterdir() will let you iterate over all the files in the replies directory.
  2. zip() will let you iterate over reps and files, and automatically stops iterating after whichever iterable runs out first.
  3. writelines() will dump all the lines in the lines variable to the file.