ngShravil.py
ngShravil.py

Reputation: 5058

Getting wrong output for a program to copy the contents of one file to another in python

I am getting wrong output even if the file exists. Following is the code...

from sys import argv
from os.path import exists
import sys
import os

script,fromf,tof=argv
inf=open(fromf)
if exists(str(inf))==True:
    indata=inf.read()
    outf=open(tof,'w')
    if exists(str(outf))==True:
        print("Error! Output file exists.")
        sys.exit()
    else:
        outf.write(indata)
        print("The task is accomplished.")
else:
    print("Error! Input file doesn't exists.")

I am passing the arguments as below....

python3 file.py aaa.txt bbb.txt

the file aaa.txt exists... but still it is showing "Error! Input file doesn't exists"

Upvotes: 0

Views: 60

Answers (3)

Jean-François Fabre
Jean-François Fabre

Reputation: 140316

you already open the file. If the file didn't exist, you'd get an exception. So your test is useless (and wrong as Reut explained).

Furthermore your "check if file exists before overwriting" feature doesn't work:

outf=open(tof,'w')
if exists(str(outf))==True:
    print("Error! Output file exists.")
    sys.exit()
else:
    outf.write(indata)
    print("The task is accomplished.")

You open the file for writing, so no need to check to see if the file exists, and the test is wrong (for the same reason) but even if it was right, it would do the opposite of the feature you wanted.

You wanted to avoid overwriting an existing file, so test before truncating it, or it's too late, and you always exit with error!

Fixed code:

if exists(tof):
    print("Error! Output file exists.")
    sys.exit()
outf=open(tof,'w')

Upvotes: 1

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339795

You can check for existence of a file by supplying the path as a string to os.path.exists. However what you are doing is supplying a file handle; therefore os.path.exists returns False even though the file exists.

I would not recomment even checking for existence. If the files exist, everything will be fine, if not, you can just capture the error using try: except.

Also, you do not close the files in your code, which can lead to problems. Better open them using the with open(filename) as filehandle syntax, which makes sure they will be closed at the end.

A full example code may look like this:

from sys import argv
import sys

script,fromf,tof=argv
try:
    with open(fromf) as inf:
        indata=inf.read()
        with open(tof,'w') as outf:
            outf.write(indata)
            print("The task is accomplished.")
except:
    print("Error!")
    sys.exit()

Upvotes: 1

Reut Sharabani
Reut Sharabani

Reputation: 31349

os.path.exists expects a path (string), not a file object.

You should use fromf as the argument:

if exists(fromf): # no need for " == True"
    # ...

Upvotes: 2

Related Questions