python -c" print''@''。join([''。''。join([w [:: - 1] for p in p.split(''。'')] )''o **** @ xiludom.gro'中的 p。分裂(''''')])" bruno at modulix写道: 谢谢,这就是我想要的。看起来有点奇怪,但至少你这个告诉我line.strip()远远好于line ==''\ n'' What is the best way of altering something (in my case, a file) whileyou are iterating over it? I''ve tried this before by accident and got anerror, naturally.I''m trying to read the lines of a file and remove all the blank ones.One solution I tried is to open the file and use readlines(), then copythat list into another variable, but this doesn''t seem very efficient tohave two variables representing the file.Perhaps there''s also some better to do it than this, including usingreadlines(), but I''m most interested in just how you edit something asyou are iterating with it.Thanks. 解决方案Slightly new question as well. here''s my code:phonelist = open(''file'').readlines()new_phonelist = phonelistfor line in phonelist:if line == ''\n'':new_phonelist.remove(line)import pprintpprint.pprint(new_phonelist)But I notice that there are still several lines that print out as ''\n'',so why doesn''t it work for all lines?If the file is huge, this can be a problem. But you cannot modify a textfile in place anyway.For the general case, the best way to go would probably be an iterator:def iterfilter(fileObj):for line in fileObj:if line.strip():yield linef = open(path, ''r'')for line in iterfilter(f):doSomethingWith(line)Now if what you want to do is just to rewrite the file without the blankfiles, you need to use a second file:fin = open(path, ''r'')fout = open(temp, ''w'')for line in fin:if line.strip():fout.write(line)fin.close()fout.close()then delete path and rename temp, and you''re done. And yes, this isactually the canonical way to do this !-)--bruno desthuillierspython -c "print ''@''.join([''.''.join([w[::-1] for w in p.split(''.'')]) forp in ''o****@xiludom.gro''.split(''@'')])"Thanks, that''s what I want. Seems a little strange, but at least youshowed me that line.strip() is far better than line == ''\n'' 这篇关于在迭代它时改变一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-15 05:59