简体   繁体   中英

Why does python output to a file like this?

Trying to have a user input their name, copy that variable to a file, and then read it back. However, when read back, it only says [][]

My code looks like this (currently)

Name = raw_input("What is your Name? ")
print "you entered ", Name
fo = open("foo.txt", "r+")
fo.write (Name)
str = fo.read();
print "Read String is : ", str
fo.close()

When I look at the foo.txt file, it has all of this inside:

Mathew” ÿÿÿÿ _getresponse:16: thread woke up: response: ('OK', {'maybesave': 1, ' format ': 1, 'runit': 1, 'remove_selection': 1, ' str ': 1, '_file_line_helper': 1, '_asktabwidth': 1, '_filename_to_unicode': 1, 'open_stack_viewer': 1, 'get_region': 1, 'cut': 1, 'open_module': 1, 'showerror': 1, ' class ': 1, 'smart_indent_event': 1, 'set_status_bar': 1, 'about_dialog': 1, 'indent_region_event': 1, 'load_extension': 1, 'set_region': 1, '_close': 1, 'cancel_callback': 1, 'postwindowsmenu': 1, ' subclasshook ': 1, 'newline_and_indent_event': 1, 'toggle_debugger': 1, 'saved_change_hook': 1, 'eof_callback': 1, 'get_warning_stream': 1, 'get_standard_extension_names': 1, 'guess_indent': 1, 'ResetFont': 1, 'center_insert_event': 1, 'replace_event': 1, 'unload_extensions': 1, 'del_word_right': 1, 'close_debugger': 1, ' EditorWindow _extra_help_callback': 1, 'python_docs': 1, 'fill_menus': 1, 'flush': 1, 'close': 1, ' setattr ': 1, 'set_notabs_indentwidth': 1, 'help_dialog': 1, 'set_saved ': 1, 'get_selection_indices': 1, 'open_debugger': 1, 'tabify_region_event': 1, 'comment_region_event': 1, 'get_var_obj': 1, 'find_selection_event': 1, '_rmcolorizer': 1, 'goto_line_event': 1, 'load_standard_extensions': 1, 'reset_undo': 1, 'long_title': 1, 'paste': 1, 'close2': 1, 'reset_help_menu_entries': 1, 'set_indentation_params': 1, 'open_class_browser': 1, 'endexecuting': 1, ' delattr ': 1, '_addcolorizer': 1, ' repr ': 1, 'close_hook': 1, 'home_callback': 1, 'right_menu_event': 1, 'getlineno': 1, 'apply_bindings': 1, 'restart_shell': 1, '_make_blanks': 1, 'get_geometry': 1, 'ApplyKeybindings': 1, 'get_tabwidth': 1, 'ResetColorizer': 1, 'open_path_browser': 1, 'filename_change_hook': 1, '_build_char_in_string_func': 1, 'isatty': 1, 'find_event': 1, 'untabify_region_event': 1, ' reduce ': 1, 'find_in_files_event': 1, 'new_callback': 1, 'getvar': 1, 'copy': 1, 'center': 1, 'writelines': 1, 'recall': 1, 'load_extensions': 1, 'showprompt': 1, 'close_event': 1, 'reindent_to': 1, 'as kinteger': 1, ' hash ': 1, 'RemoveKeybindings': 1, 'dedent_region_event': 1, 'linefeed_callback': 1, 'is_char_in_string': 1, ' getattribute ': 1, 'move_at_edge_if_selection': 1, 'beginexecuting': 1, 'enter_callback': 1, 'short_title': 1, 'getwindowlines': 1, 'smart_backspace_event': 1, ' sizeof ': 1, 'set_tabwidth': 1, 'find_again_event': 1, ' init ': 1, 'del_word_left': 1, 'get_saved': 1, ' reduce_ex ': 1, ' new ': 1, 'select_all': 1, 'gotoline': 1, 'view_restart_mark': 1, 'change_indentwidth_event': 1, 'write': 1, 'set_debugger_indicator': 1, 'config_dialog': 1, 'set_warning_stream': 1, 'setvar': 1, 'createmenubar': 1, 'begin': 1, 'toggle_tabs_event': 1, 'askyesno': 1, 'ispythonsource': 1, 'resetoutput': 1, 'set_close_hook': 1, 'goto_file_line': 1, 'readline': 1, 'toggle_jit_stack_viewer': 1, 'make_rmenu': 1, ' EditorWindow _recent_file_callback': 1, 'uncomment_region_event': 1, 'update_recent_files_list': 1, 'set_line_and_column': 1}) ã èã”po” èã”po”

Any idea why?

First, you've opened the file in mode "r+" which is read-write. This will not empty the file, and anything you write will overwrite existing bytes. This is almost certainly not what you want: either 'a' if you want to append to the file, or 'w' if you want to delete the file first if it already exists.

Second, you're reading from where the write left off, and not repositioning the file cursor. In fact it's slightly worse than that: behavior of file objects isn't very well defined if you don't seek between reads and writes.

From C reference for fopen

For the modes where both read and writing (or appending) are allowed (those which include a "+" sign), the stream should be flushed (fflush) or repositioned (fseek, fsetpos, rewind) between either a reading operation followed by a writing operation or a writing operation followed by a reading operation.

The Python reference makes it clear that open() is implemented using standard C file objects.

Here's what I would write:

with open('foo.txt', 'w') as f:
    f.write(name)
with open('foo.txt', 'r') as f:
    print 'Text is:', f.read()

The with statement is nice here as it automatically closes the file once the write is done. By closing the file and reopening it in read mode, you guarantee that the written text made it into the file and isn't being cached.

As for why you get nothing back, that's probably because you have to seek to the beginning first:

fo.seek(0)
result = fo.read()

There is a pointer which marks the "current" position in a file. When you open a file, it is set at the beginning of the file. Next thing you do is write to it. As you write, the pointer keeps advancing. When you have written completely, the pointer is at the end of the file. And if you start reading then (which is what you are doing here), you'll get nothing but junk. So, you need to reset the pointer to the beginning before you start reading which can be done by seek as you can see above or you can close the file after writing and open it again before reading.

Name = raw_input("What is your Name? ")
print "you entered ", Name
fo = open("foo.txt", "r+")
fo.write (Name)
fo.flush()
fo.close()
fo = open("foo.txt", "r+")
str = fo.read();
print "Read String is : ", str
fo.close()

It is also a good idea to call flush() after writing to the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM