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
34 txt
files have been replaced then it's donehow can I achieve this?
I would be very appreciate
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.