Thursday, 15 April 2010

python - Why file gets empty when creating open objects in different modes? -



python - Why file gets empty when creating open objects in different modes? -

i'm writing simple parser. now, reads whole current dir , open files 'r' , 'w' permissions files end ".w". here's code it:

import os wc_dir = os.path.dirname(os.path.abspath(__file__)) files = [f f in os.listdir(wc_dir) if os.path.isfile(os.path.join(wc_dir,f))] comp_files_r = [open(f, 'r') f in files if f.endswith(".w")] comp_files_w = [open(f, 'w') f in files if f.endswith(".w")]

as can see, have 2 lists "open objects" read , write permissions files in current folder end ".w". now, have 1 file. so, consider following:

print comp_files_r print comp_files_w

output:

[<open file 'app.w', mode 'r' @ 0x7effd48274b0>] [<open file 'app.w', mode 'w' @ 0x7effd4827540>]

it happens that, when seek read 'app.w' file:

def parse(): f in comp_files_r: f file: info = file.read() print repr(data) parse()

i astonishing empty string no reason. i've managed find that, save in 'app.w' gets erased when execute code "w list comprehension". why that? i've learned pain trying both read , write file in "r+" mode can lead weird results. that's not situation. i've created different objects same file, , this messing content of file itself. why?

it looks me issue you're opening file in 'w' mode. when open file in 'w' mode, current file deleted , replaced new file. 'r+' mode reading , editing.

i'd willing bet if read contents of files between lines open them reading , and line open them writing, see contents of files expect them be.

python file

No comments:

Post a Comment