Why doesn't the character count \n?


Here is a simple program from a textbook. I input the the text file Students.txt which is


and f2 is some randomly named folder that does not exist in the current working directory. Now when I input Students.txt and Attendance.txt, it prints out 10 characters. Why? When the pointer goes through Students.txt shouldn’t it look like


The last \n should be there because of the existence of line 3. So why does it print 10 instead of 12? Thanks

import os.path
import sys

def main():
    # Prompt the user to enter filenames
    f1 = input("Enter source file: ").strip()
    f2 = input("Enter target file: ").strip()

    # Check if target file exists
    if os.path.isfile(f2):
        print(f2 + " already exists")

    # Open files for input and output
    infile = open(f1, "r")
    outfile = open(f2, "w")

    # Copy from input file to output file
    countLines = countChars = 0
    for line in infile:
        countLines += 1
        countChars += len(line)
    print(countLines, "lines and", countChars, "chars copied")

    infile.close()  # Close the input file
    outfile.close()  # Close the output file

if __name__ == "__main__":
    main()  # Call the main function


because \n is a single character:



This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.