重新打开Python中的文件? [英] Re-open files in Python?

查看:84
本文介绍了重新打开Python中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这个简单的python脚本:

Say I have this simple python script:

file = open('C:\\some_text.txt')
print file.readlines()
print file.readlines()

运行时,第一个打印将打印一个包含文件文本的列表,而第二个打印将打印一个空白列表.我猜不是完全出乎意料的.但是,是否有一种方法可以回退"文件,以便我可以再次读取它?还是最快的方法只是重新打开它?

When it is run, the first print prints a list containing the text of the file, while the second print prints a blank list. Not completely unexpected I guess. But is there a way to 'wind back' the file so that I can read it again? Or is the fastest way just to re-open it?

推荐答案

您可以通过调用 seek() :

You can reset the file pointer by calling seek():

file.seek(0)

会做到的.您的第一个readlines()之后需要该行.请注意,file必须支持随机访问才能使以上内容正常工作.

will do it. You need that line after your first readlines(). Note that file has to support random access for the above to work.

这篇关于重新打开Python中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆