而c = f.read(1) [英] while c = f.read(1)

查看:111
本文介绍了而c = f.read(1)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python代码段:


f = open(" blah.txt"," r")

而True:

c = f.read(1)

if c =='''':break#EOF

#...在c上工作

是否有一些方法可以使这段代码更紧凑和简单?这是一点点

spaghetti。


这就是我理想的样子:


f = open( " blah.txt"," r")

而c = f.read(1):

#...工作c


但我收到语法错误。


而c = f.read(1):

^

语法错误:语法无效


而且read()无论如何也不会这样,因为它在EOF上返回''''
和' '''!=假。如果我尝试:


f = open(blah.txt,r)

while(c = f.read(1)) !='''':

#...在c上工作

我也遇到语法错误。 :(


这是否与Python的表达式与语句句法相关

分离?我怎样才能更好地编写这段代码?


谢谢

I have a Python snippet:

f = open("blah.txt", "r")
while True:
c = f.read(1)
if c == '''': break # EOF
# ... work on c

Is some way to make this code more compact and simple? It''s a bit
spaghetti.

This is what I would ideally like:

f = open("blah.txt", "r")
while c = f.read(1):
# ... work on c

But I get a syntax error.

while c = f.read(1):
^
SyntaxError: invalid syntax

And read() doesn''t work that way anyway because it returns '''' on EOF
and '''' != False. If I try:

f = open("blah.txt", "r")
while (c = f.read(1)) != '''':
# ... work on c

I get a syntax error also. :(

Is this related to Python''s expression vs. statement syntactic
separation? How can I be write this code more nicely?

Thanks

推荐答案

2005年8月18日22:21:53 -0700,Greg McIntyre"< gr ** @ puyo.cjb.net>写道:
On 18 Aug 2005 22:21:53 -0700, "Greg McIntyre" <gr**@puyo.cjb.net> wrote:
我有一个Python片段:

f = open(< blah。 txt"," r")
而True:
c = f.read(1)
如果c =='''':中断#EOF
#..工作上的问题

是否有一些方法可以使这个代码更紧凑和简单?它有点意大利面。

这就是我理想的样子:

f = open(" blah.txt"," r")
而c = f.read(1):
#...在c上工作

如何(未经测试):


for c in iter((lambda f = open(''blah.txt'',''r'' ):f.read(1)),''''):

#...在c上工作


(" if c =='''':break"功能礼貌上面的iter(f,sentinel)形式)


当然,逐个阅读字符效率不高,所以如果文件

是合理的大小,你可能只想阅读整个事情并通过它迭代

,比如


for c in open(''blah.txt' ')。read():

#...工作c

但我得到语法错误。

而c = f。 read(1):
^
SyntaxError:语法无效

并且read()无论如何也不会这样,因为它在EOF上返回'''' >和''''!=错误。如果我尝试:

f = open(blah.txt,r)
while(c = f.read(1))!='''':
#...工作c

我也遇到语法错误。 :(

这是否与Python的表达式与语句语法分离有关?我怎样才能更好地编写这段代码?
I have a Python snippet:

f = open("blah.txt", "r")
while True:
c = f.read(1)
if c == '''': break # EOF
# ... work on c

Is some way to make this code more compact and simple? It''s a bit
spaghetti.

This is what I would ideally like:

f = open("blah.txt", "r")
while c = f.read(1):
# ... work on c
How about (untested):

for c in iter((lambda f=open(''blah.txt'', ''r''): f.read(1)), ''''):
# ... work on c

("if c=='''': break" functionality courtesy of iter(f, sentinel) form above)

Of course, reading characters one by one is not very efficient, so if the file
is reasonably sized, you might just want to read the whole thing and iterate
through it, something like

for c in open(''blah.txt'').read():
# ... work on c
But I get a syntax error.

while c = f.read(1):
^
SyntaxError: invalid syntax

And read() doesn''t work that way anyway because it returns '''' on EOF
and '''' != False. If I try:

f = open("blah.txt", "r")
while (c = f.read(1)) != '''':
# ... work on c

I get a syntax error also. :(

Is this related to Python''s expression vs. statement syntactic
separation? How can I be write this code more nicely?



是的,它与您怀疑有关。我会留给您制作

a chunk-buffering one-liner,用于按字符迭代的大型文件,

如果单行打开你。否则很容易编写一个能够做到的发电机。

到我发布时,有人可能会这样做;-)

问候,

Bengt Richter


Yes, it is related as you suspect. I''ll leave it to you to make
a chunk-buffering one-liner for huge files that iterates by characters,
if one-liners turn you on. Otherwise it is easy to write a generator that will do it.
Byt the time I post this, someone will probably have done it ;-)
Regards,
Bengt Richter


Greg McIntyre写道:
Greg McIntyre wrote:
我有一个Python片段:

f = open(" blah.txt"," r")
而True:
c = f.read(1)
如果c ==' ''':打破#EOF
#...工作c

是否有一些方法可以使这段代码更紧凑和简单?这有点意大利面条。
I have a Python snippet:

f = open("blah.txt", "r")
while True:
c = f.read(1)
if c == '''': break # EOF
# ... work on c

Is some way to make this code more compact and simple? It''s a bit
spaghetti.




这不是意大利面条。甚至没有关闭。


在任何情况下,你是否有理由一次读一个字符

而不是将文件内容读入内存并在结果字符串上迭代



f = open(''blah.txt'',''r'')

text = f.read()

f.close()


for c in f:

#.. 。


如果你必须一次读一个字符,


def reader(fileobj,blocksize = 1):

"""返回从

文件对象读取给定大小的块的迭代器,直到EOF。

"""

#注意iter()可以使用一个函数来重复调用,直到它获得给定的哨兵值,这里是''''。

返回iter(lambda:fileobj.read(blocksize),'''')


f = open(''blah.txt'',''r'')

尝试:

for c in reader(f):

#...

最后:

f.close()


-

Robert Kern
rk *** @ ucsd.edu


在草地长得高的地狱里

是否允许死亡的坟墓死亡。

- Richard Harter



That''s not spaghetti. Not even close.

In any case, is there a reason you are reading one character at a time
instead of reading the contents of the file into memory and iterating
over the resulting string?

f = open(''blah.txt'', ''r'')
text = f.read()
f.close()

for c in f:
# ...

If you must read one character at a time,

def reader(fileobj, blocksize=1):
"""Return an iterator that reads blocks of a given size from a
file object until EOF.
"""
# Note that iter() can take a function to call repeatedly until it
# receives a given sentinel value, here ''''.
return iter(lambda: fileobj.read(blocksize), '''')

f = open(''blah.txt'', ''r'')
try:
for c in reader(f):
# ...
finally:
f.close()

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter


Quoth" Greg麦金太尔" < gr ** @ puyo.cjb.net>:

|我有一个Python片段:

|

| f = open(" blah.txt"," r")

|而真:

| c = f.read(1)

|如果c =='''':break#EOF

| #...工作c

|

|有一些方法可以使这个代码更紧凑和简单吗?这有点

|意大利面。


实际上我会让它变得不那么紧凑 - 把破解

放在自己的路线上 - 但是在任何地方这很好。这是一个自然的

和用Python表达的普通方式。


....

|但是我收到语法错误。

|

|而c = f.read(1):

| ^

| SyntaxError:语法无效

|

|并且read()无论如何也不会这样,因为它在EOF上返回''''
|和''''!=假。如果我尝试:


这是我真正想要回应的部分。 Python管理

多年没有假(当然没有True),如果

引入这种多余的布尔类型真的导致了
$ b对于这种混乱的大部分是$ b,那肯定是个坏主意。


我们在这里看的条件,这通常是

在Python中查看条件表达式的方法,基本上是

。在这个和大多数IO读取中,返回

值将是一些东西,直到文件末尾它什么都没有。

任何类型的没什么 - ''' ',{},[],0,无 - 将测试false,

,其他所有内容均为true。当然,True也是如此,并且

假是假的,但据我所知,他们从未真正需要。


毫无疑问想知道我什么时候才能到达

的部分你可以利用它来为你节省这3行代码。对不起,

它没有帮助。


|这与Python的表达式与语句句法有关吗

|分离?我怎样才能更好地编写这段代码?


是的,确切地说。别担心,这很好。如果这是你的代码中最糟糕的问题,那么你比我们的大多数人要好得多。


Donn Cave, do**@drizzle.com
Quoth "Greg McIntyre" <gr**@puyo.cjb.net>:
| I have a Python snippet:
|
| f = open("blah.txt", "r")
| while True:
| c = f.read(1)
| if c == '''': break # EOF
| # ... work on c
|
| Is some way to make this code more compact and simple? It''s a bit
| spaghetti.

Actually I''d make it a little less compact -- put the "break"
on its own line -- but in any case this is fine. It''s a natural
and ordinary way to express this in Python.

....
| But I get a syntax error.
|
| while c = f.read(1):
| ^
| SyntaxError: invalid syntax
|
| And read() doesn''t work that way anyway because it returns '''' on EOF
| and '''' != False. If I try:

This is the part I really wanted to respond to. Python managed
without a False for years (and of course without a True), and if
the introduction of this superfluous boolean type really has led
to much of this kind of confusion, then it was a bad idea for sure.

The condition that we''re looking at here, and this is often the
way to look at conditional expressions in Python, is basically
something vs. nothing. In this and most IO reads, the return
value will be something, until at end of file it''s nothing.
Any type of nothing -- '''', {}, [], 0, None - will test "false",
and everything else is "true". Of course True is true too, and
False is false, but as far as I know they''re never really needed.

You are no doubt wondering when I''m going to get to the part where
you can exploit this to save you those 3 lines of code. Sorry,
it won''t help with that.

| Is this related to Python''s expression vs. statement syntactic
| separation? How can I be write this code more nicely?

Yes, exactly. Don''t worry, it''s nice as can be. If this is
the worst problem in your code, you''re far better off than most
of us.

Donn Cave, do**@drizzle.com


这篇关于而c = f.read(1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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