Why doesn't the character count \n?


#1

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

57%20PM

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

Greg\nToby\n

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")
        sys.exit()

    # 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:
        print(repr(line))
        countLines += 1
        countChars += len(line)
        outfile.write(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


#2

because \n is a single character:

https://stackoverflow.com/questions/15601824/is-the-newline-n-2-characters-or-1-character


#3

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