Python文件变量 - 它是什么? [英] Python file variable - what is it?

查看:131
本文介绍了Python文件变量 - 它是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用Python,由于我的背景是更低级的语言(Java,C ++),所以我只是无法得到一些东西。因此,在Python中,可以通过打开一个文本文件来创建一个文件变量,例如,然后遍历它的行:

  f = open(sys.argv [1])$ ​​b $ b for $ f 
$ do

然而,如果我尝试 f [0] 错误。那么 f 对象有什么结构,我怎么知道一般情况下,如果我可以在...中使用 ...:循环到一个对象?

文件对象。该文档列出了它的结构,所以我只会解释索引/迭代行为。

只有实现 __ getitem __ ,你可以通过调用 hasattr(f,'__getitem __')或者只是调用 f [0] 看看是否会抛出一个错误。事实上,这正是你的错误信息所告诉你的:

pre code> TypeError:'file'对象没有属性'__getitem__'

文件对象不可索引。您可以调用 f.readlines()并返回一行,它本身是可索引的。



可以使用 for ... in ... 语法来实现 __ iter __ 。现在实际上有两种类型的可迭代对象:容器对象和迭代器对象。迭代器对象实现了两个方法: __ iter __ __ next __ 。容器对象只实现 __ iter __ 并返回一个迭代器对象,这实际上就是迭代的对象。文件对象是它们自己的迭代器,因为它们实现了这两种方法。



如果要获取迭代中的下一个项目,可以使用下一步()函数:

pre $ $ $ $ $ $ $ $ $ $ $ $ $ f)
next_line_that_starts_with_0 = next(line for line in line.startswith('0'))



一个小心点:迭代器通常不是可回放的,所以一旦通过迭代器进展,就不能真正回头。要倒回文件对象,可以使用 f.seek(0),这会将当前位置设置回文件的开头。 b $ b

I just started with Python, and since my background is in more low-level languages (java, C++), i just cant really get some things.

So, in python one can create a file variable, by opening a text file, for example, and then iterate through its lines like this:

f = open(sys.argv[1])
for line in f:
    #do something

However, if i try f[0] the interpreter gives an error. So what structure does f object have and how do i know in general, if i can apply for ... in ... : loop to an object?

解决方案

f is a file object. The documentation lists its structure, so I'll only explain a the indexing/iterating behavior.

An object is indexable only if it implements __getitem__, which you can check by calling hasattr(f, '__getitem__') or just calling f[0] and seeing if it throws an error. In fact, that's exactly what your error message tells you:

TypeError: 'file' object has no attribute '__getitem__'

File objects are not indexable. You can call f.readlines() and return a list of lines, which itself is indexable.

Objects that implement __iter__ are iterable with the for ... in ... syntax. Now there are actually two types of iterable objects: container objects and iterator objects. Iterator objects implement two methods: __iter__ and __next__. Container objects implement only __iter__ and return an iterator object, which is actually what you're iterating over. File objects are their own iterators, as they implement both methods.

If you want to get the next item in an iterable, you can use the next() function:

first_line = next(f)
second_line = next(f)
next_line_that_starts_with_0 = next(line for line in f if line.startswith('0'))

One word of caution: iterables generally aren't "rewindable", so once you progress through the iterable, you can't really go back. To "rewind" a file object, you can use f.seek(0), which will set the current position back to the beginning of the file.

这篇关于Python文件变量 - 它是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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