简体   繁体   English

为什么python输出到这样的文件?

[英]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: 当我查看foo.txt文件时,它包含所有这些内容:

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 Mathew”ÿÿÿÿ_getresponse:16:线程唤醒:响应:('OK',{'maybesave':1,' format ':1,'runit':1,'remove_selection':1,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 ':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,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” kinteger':1,'' hash ':1,'RemoveKeybindings':1,'dedent_region_event':1,'linefeed_callback':1,' is_char_in_string ':1,'getattribute':1,1,'move_at_edge_if_selection':1,'开始执行: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,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. 首先,您已经以可读写模式“ r +”打开了文件。 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. 几乎可以肯定这不是您想要的:如果要附加到文件,则为'a',如果要先删除文件(如果已存在),则为'w'。

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 C参考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. 对于同时允许读取和写入(或附加)(包括“ +”号的模式)的模式,应在两次读取操作之间进行刷新(fflush)或重新定位(fseek,fsetpos,rewind)流,然后再进行写入操作或写入操作,然后进行读取操作。

The Python reference makes it clear that open() is implemented using standard C file objects. Python参考清楚表明open()是使用标准C文件对象实现的。

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. with语句在这里很好,因为一旦写入完成,它将自动关闭文件。 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. 写入文件后调用flush()也是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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