0

For instance here I'm trying to move the contents of file1 into file 2; and this is the code for my attempt which does not work. What's the problem with my code and is there a more efficient method?

file1 = open("textfile.txt", "r")
file2 = open("second textfile.txt","w")
lines = file1.readlines()
for i in range(len(lines)):
    file2.write(lines[i]+"\n")

This question is different from other questions of similar type - as it's solution is specific to coding in python.

  • Does this answer your question? [How do I copy a file in Python?](https://stackoverflow.com/questions/123198/how-do-i-copy-a-file-in-python) – costaparas Dec 24 '20 at 11:23

1 Answers1

1

If you want to copy the content of one file into an other you can do it like this:

firstfile = "textfile.txt"
secondfile = "second textfile.txt"

with open(firstfile, "r") as file:
    content = file.read()
    file.close()
    with open(secondfile, "w") as target:
        target.write(content)
        target.close()
Mark7888
  • 823
  • 1
  • 8
  • 20