Jupyter Notebook中跨单元格传递KML文件内容问题
问题原因
你遇到的问题是文件对象的read()方法会将文件指针移动到文件末尾。第一次调用print(f.read())已经把文件内容全部读完,指针停在末尾,第二次调用mytext = f.read()时,已经没有内容可以读取,所以得到空字符串。
解决方案
有两种简单的修复方式:
方式一:先读取内容到变量,再打印
先把文件内容读取到mytext变量中,再打印变量内容,这样既完成了打印,也保留了内容到变量里:
# Print the selected path, filename, or both print(fc.selected_path) print(fc.selected_filename) print(fc.selected) global mytext with open(fc.selected, 'r') as f: mytext = f.read() print(mytext)
方式二:重置文件指针到开头
在第一次读取后,调用f.seek(0)将文件指针移回文件开头,再进行第二次读取:
# Print the selected path, filename, or both print(fc.selected_path) print(fc.selected_filename) print(fc.selected) global mytext with open(fc.selected, 'r') as f: print(f.read()) f.seek(0) # 把文件指针重置到文件起始位置 mytext = f.read()
之后在后续单元格直接打印mytext就能获取到文件内容了。
内容的提问来源于stack exchange,提问作者user1592380
相关产品推荐
相关产品推荐

