Search code examples
pythontext-files

printing the content of a file, but getting an int as an output (number of characters in the file) in Python


I wrote a function that copies the content of one file to a new file. the function gets 2 parameters:

  1. the directory of the copied file
  2. the directory of the new file.

When I try to print the content of the copied file, I get the content of the file (which is what I want), But when I try to do the same thing with the new file, I get the number of characters inside the file (14 in this case).

I don't understand why do I get 2 different outputs with the same (at list as per my understanding) lines of code.

Would be happy to get some help, thank you!

Here's my code:

# creating the file that's going to be copied:
with open(source_link, 'w') as f:
    f.write('Copy this file')

# the function:
def copy_file_content(source, destination):
    
    # getting the content of the copied file:
    f1 = open(source, 'r')
    copied_file = f1.read()
    f1.close()
    
    # putting the content of the copied file in the new file:
    f2 = open(destination, 'w')
    new_file = f2.write(copied_file)
    f2.close

    # print old file:
    print(copied_file)
    
    print('***')
    # print new file:
    print(new_file)
    
copy_file_content(source = source_link, destination = dest_link)

Output:

Copy this file
***
14

Solution

  • .read() returns the file contents, which is why when copied_file is set to f1.read(), you can print the contents out. However, .write() performs the write operation on the file and then returns the number of characters written.

    Therefore new_file contains the number of characters written. Rather than setting the value of new_file to f2.write(), you must open the new file again in read mode, and then perform file.read()

    def copy_file_content(source, destination):
    
        # getting the content of the copied file:
        with open(source, 'r') as f1:
            copied_file = f1.read()
        
        # putting the content of the copied file in the new file:
        with open(destination, 'w') as f2:
             f2.write(copied_file)
    
        with open(destination, "r") as f2_read:
             new_file = f2_read.read()
    
        # print old file:
        print(copied_file)
        
        print('***')
        # print new file:
        print(new_file)
        
    copy_file_content(source = source_link, destination = dest_link)