Record text from one.txt to another.txt Python 3

Hello everyone

There are three .a txt file with a different number of lines of text in each.

We compare the number of lines in each file and in the new file, the fourth one .txt, we transfer the text that has the fewest lines.

The problem occurs when writing all the text to a new file.

Here is the code:

with open ('1.txt', encoding='utf-8') as f:
    line_count1 = 0
    for line in f:
        line_count1 += 1
    print(line_count1)

with open('2.txt', encoding='utf-8') as f1:
    line_count2 = 0
    for line in f1:
        line_count2 += 1
    print(line_count2)

with open('3.txt', encoding='utf-8') as f2:
    line_count3 = 0
    for line in f2:
        line_count3 += 1
    print(line_count3)

with open('all123.txt', 'w', encoding='utf-8') as f3:
if (line_count2 < line_count1) and (line_count2 < line_count3):
    f3.writelines(f1)

What could be the problem in writing the file?

The only thing that happens is when I copy the text from the file and paste it just into write() everything goes away of course.

I'm just learning.

Author: skuch, 2020-11-27

2 answers

After you read the file for line in f: once, it became empty

You need to re-open the file

with open('all123.txt', 'w', encoding='utf-8') as f3:
    if (line_count2 < line_count1) and (line_count2 < line_count3):
        with open("1.txt", encoding="utf-8") as f1:
            f3.writelines(f1.readlines())
 0
Author: Danis, 2020-11-27 20:10:54

From f1 , you first need to read the rows in the list, since you can only read the data once from the handle:

with open(...) as f1: 
    f1_lines = [l for l in f1.readlines()]
    line_count2 = len(f1_lines)
...
if (line_count2 < line_count1) and (line_count2 < line_count3):
    f3.writelines(f1_lines)

We do the same with other f file descriptors :)

There must also be a newline character at the end of each line:

f3.writelines([f'{l}\n' for l in f1_lines])
 1
Author: roddar92, 2020-11-27 20:15:11