sheeraz mohammed
sheeraz mohammed

Reputation: 1

How do you copy the contents of one file to another in python? -I have also include the code for my failed attempt

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.

Upvotes: 0

Views: 59

Answers (1)

Mark7888
Mark7888

Reputation: 853

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()

Upvotes: 1

Related Questions