1

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")
3
  • No, you should use the context manager; with open("foo.txt") as fo, open("out.txt", "w") as foo:
    – jonrsharpe
    Commented Jan 9, 2015 at 21:13
  • You should read some tutorials about python programming. But as a start, check out shutil.
    – tdelaney
    Commented Jan 9, 2015 at 21:13
  • print inside out.txt using foo.write()? @jonrsharpe
    – hvardhan
    Commented Jan 9, 2015 at 21:16

2 Answers 2

1

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")
1

You can use:

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.