I’m very new to coding and the book has done wonders for me so far.
After completing ex17 I decided to give myself a challenge based on it, basically I wanted to open a file, copy the contents of it by storing it in a variable, ask the user for input, store that in a variable and rewrite the destination file by adding these two variables to it.
Here is my code:
print("Copying a file to add it to another file!") from sys import argv from os.path import exists #Technicaly don't need that here(?) script, from_file, to_file = argv from_file = open(from_file) print("Your file contents:") print(from_file.read()) contents = from_file.read() print("Is there anything you would like to add to the destination file? \n(leave empty if not)... ") contents2 = input("") to_file = open(to_file, 'w+') to_file.write(contents + contents2) #Now I want to read what I've done print("Let's read our new file:") to_file.seek(0) print(to_file.read()) from_file.close() to_file.close()
The problem is it doesn’t seem to save the contents of the
from_file from this:
contents = from_file.read()
Even though it does print it when I gave it the command to before
(BTW is the output in the shell suppose to be all specey? it also gives me weird characters I never put in there ( ÿþ - to be specific ))
So when I finally tell it to print the new file it just prints me the contents of
I get no error but the program doesn’t work like I planned it. I realize I may have made a mess of things so I also included the output that I got in the Shell:
> echo "This is a test file"> test.txt > python ex17a.py test.txt new_testfor17.txt Copying a file to add it to another file! Your file contents: ÿþT h i s i s a t e s t f i l e Is there anything you would like to add to the destination file? (leave empty if not)... okay Let's read our new file: okay