Python Forum
Do not get how Python iterates over a file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Do not get how Python iterates over a file
#11
you guys are awesome!
I learned something new today...

Thank you!
Reply
#12
The code you provided is using the zip function to iterate over both files, line by line, and print the values. However, the zip function stops iterating when the shortest iterable is exhausted. In this case, it stops after the first file (File1) is exhausted, so it only prints the first three lines of the second file (File2).

To merge the two files as you described, you can use the extend method of a list to add the contents of one file to the other.
with open("file1.txt") as file1, open("file2.txt") as file2:
    lines = file1.readlines()
    lines.extend(file2.readlines())
    for line in lines:
        print(line)
This will read the contents of both files into a list, then add the contents of the second file to the end of the first file and print each line.

Alternatively you can use the itertools.chain method, to merge the files:
import itertools

with open("file1.txt") as file1, open("file2.txt") as file2:
    for line in itertools.chain(file1, file2):
        print(line)
This will read the contents of both files and merge them together, and print each line as it reads them.
buran write Jan-28-2023, 07:17 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#13
You could use fileinput to read many files.

import fileinput


files = fileinput.input(("file1.txt", "file2.txt"), encoding="utf8")

for line in files:
    lineno = files.lineno()
    filename = files.filename()
    filelineno = files.filelineno()
    print(f"[{filename:<15}] [{filelineno:>4d}]: {line}", end="")
So, if you need the current file, line number and total line number, you could use this.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Still do not get how Python iterates over a file tester_V 13 3,634 Aug-24-2021, 05:10 AM
Last Post: naughtyCat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020