0

i have this mini-script:

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

    p_script, p_from_file, p_to_file = argv

    print ('Copying from {first} to {second}'.format(first = p_from_file, 
                                                     second = p_to_file))

    v_in_file = (open(p_from_file, 'r')).read()
    print (v_in_file)

    print ('The input file is {size} bytes long'.format(size = len(v_in_file)))
    print ('Does the output file exists? {boolean}'.format(boolean = exists(p_to_file)))
    raw_input('Press return to continue...')

    v_out_file = open(p_to_file, 'w')
    v_out_file.write(v_in_file)

    print ('Alright, all done.')
    v_in_file.close()
    v_out_file.close()

Problem is..i can't close the file and i don't know why, what's the problem? "v_in_file.close()" doesn't executes properly.

udarH3
  • 199
  • 2
  • 5
  • 16
  • `v_in_file` is **the data you `read` from the file**, not the file handle itself... Also, use the context manager `with`. – jonrsharpe May 28 '15 at 15:56

2 Answers2

1

You are creating a file inside the ( ) and requesting the .read() method so resulting at a String value, after that you lose your file object

best way is to create the file to a variable and after you read from it, so you can close it properly after usage

Try this:

from sys import argv
from os.path import exists

p_script, p_from_file, p_to_file = argv

print ('Copying from {first} to {second}'.format(first = p_from_file, 
                                                 second = p_to_file))

file_to_read = open(p_from_file, 'r')
v_in_file = file_to_read.read()
print (v_in_file)

print ('The input file is {size} bytes long'.format(size = len(v_in_file)))
print ('Does the output file exists? {boolean}'.format(boolean = exists(p_to_file)))
raw_input('Press return to continue...')

v_out_file = open(p_to_file, 'w')
v_out_file.write(v_in_file)

print ('Alright, all done.')
file_to_read.close()
v_out_file.close()

As per recommended by the buddie below you can check using with here

Community
  • 1
  • 1
Solano
  • 550
  • 2
  • 9
  • 2
    You should use `with` for file handling, e.g. `with open(p_from_file) as file_to_read:`. Then you don't have to `close`. – jonrsharpe May 28 '15 at 15:57
1

Your v_in_file is a string evaluating to the contents of p_from_file. (Python documentation). As such, it has no close() method.

You could instead write,

v_in_file = open(p_from_file, 'r') file_text = v_in_file.read() v_in_file.close()

or

with open(p_from_file, 'r') as v_in_file: file_text = v_in_file.read()

to automatically close the file [thanks for the reminder, jonrsharpe]

Dan Ambrogio
  • 356
  • 2
  • 10
  • it was written like your first example, but i was asked to try to write it on a single line the whole thing..anyway, thanks! – udarH3 May 28 '15 at 16:48