hvardhan
hvardhan

Reputation: 470

Reading/Writing to a file in Python

I have a python code with some print statements.Now, I want to read input from one file and output it to another file.How do i do it ? Should i include this ?

code :

fo = open("foo.txt", "r")
foo = open("out.txt","w")

Upvotes: 1

Views: 237

Answers (2)

Reut Sharabani
Reut Sharabani

Reputation: 31339

Naive way:

fo = open("foo.txt", "r")
foo = open("out.txt","w")
foo.write(fo.read())
fo.close()
foo.close()

Better way, using with:

with open("foo.txt", "r") as fo:
    with open("out.txt", "w") as foo:
        foo.write(fo.read())

Nice way (using a module that does it for you - shutil.copy):

from shutil import copy
copy("foo.txt", "out.txt")

Upvotes: 1

Coder-256
Coder-256

Reputation: 5618

You can use:

with open("foo.txt", "r") as fo, open("out.txt", "w") as foo:
    foo.write(fo.read())

Upvotes: 1

Related Questions