繁体   English   中英

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

[英]Why does python output to a file like this?

尝试让用户输入名称,然后将该变量复制到文件中,然后再读回。 但是,回读时只说[] []

我的代码如下所示(当前)

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()

当我查看foo.txt文件时,它包含所有这些内容:

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,1,'as 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”

知道为什么吗?

首先,您已经以可读写模式“ r +”打开了文件。 这不会清空文件,并且您编写的任何内容都将覆盖现有字节。 几乎可以肯定这不是您想要的:如果要附加到文件,则为'a',如果要先删除文件(如果已存在),则为'w'。

其次,您将从停止写入的位置开始读取,而不是重新定位文件光标。 实际上,这还比这稍差一点:如果不在读写之间寻找文件对象的行为,则无法很好地定义文件对象的行为。

C参考fopen

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

Python参考清楚表明open()是使用标准C文件对象实现的。

这是我要写的:

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

with语句在这里很好,因为一旦写入完成,它将自动关闭文件。 通过关闭文件并在读取模式下重新打开它,可以确保书面文本将其放入文件中并且不会被缓存。

至于为什么您什么也得不到,那可能是因为您必须首先寻找起点:

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

有一个指针标记文件中的“当前”位置。 当您打开文件时,该文件将设置在文件的开头。 接下来要做的就是写它。 在编写时,指针不断前进。 完全编写完之后,指针将位于文件的末尾。 然后,如果您开始阅读(这就是您在这里所做的事情),那么您只会得到垃圾。 因此,您需要在开始读取之前将指针重置为开始,这可以通过如上所见的查找来完成,或者可以在写入后关闭文件,然后在读取之前再次打开它。

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()

写入文件后调用flush()也是一个好主意。

暂无
暂无

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

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