python 如何输出文件中的每一行
if data.find('!masters') != -1:
f = open('masters.txt')
lines = f.readline()
for line in lines:
print lines
sck.send('PRIVMSG ' + chan + " " + str(lines) + '\r\n')
f.close()
masters.txt 有一个昵称列表,我如何一次打印文件中的每一行?我的代码只打印第一个昵称。我们将不胜感激您的帮助。谢谢。
if data.find('!masters') != -1:
f = open('masters.txt')
lines = f.readline()
for line in lines:
print lines
sck.send('PRIVMSG ' + chan + " " + str(lines) + '\r\n')
f.close()
masters.txt has a list of nicknames, how can I print every line from the file at once?. The code I have only prints the first nickname. Your help will be appreciate it. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
首先,正如 @l33tnerd 所说,
f.close
应该位于 for 循环之外。其次,您仅在循环之前调用 readline 一次。这只读取第一行。诀窍在于,在 Python 中,文件充当迭代器,因此您可以迭代文件而无需调用其上的任何方法,并且每次迭代将为您提供一行:
最后,您引用的是变量
lines
在循环内;我假设您的意思是指line
。编辑:哦,您需要缩进
if
语句的内容。Firstly, as @l33tnerd said,
f.close
should be outside the for loop.Secondly, you are only calling
readline
once, before the loop. That only reads the first line. The trick is that in Python, files act as iterators, so you can iterate over the file without having to call any methods on it, and that will give you one line per iteration:Finally, you were referring to the variable
lines
inside the loop; I assume you meant to refer toline
.Edit: Oh and you need to indent the contents of the
if
statement.您可能想要类似的东西:
不要在循环的每次迭代中关闭它并打印行而不是行。还可以使用 readlines 来获取所有行。
编辑删除了我的其他答案 - 本次讨论中的另一个答案是比我的更好的选择,因此没有理由复制它。
还用 read().splitlines() 去掉了 \n
You probably want something like:
Don't close it every iteration of the loop and print line instead of lines. Also use readlines to get all the lines.
EDIT removed my other answer - the other one in this discussion is a better alternative than what I had, so there's no reason to copy it.
Also stripped off the \n with read().splitlines()
你可以试试这个。它不会立即将所有 f 读入内存(使用文件对象的迭代器),并且当代码离开 with 块时关闭文件。
如果你使用旧版本的 python(2.6 之前),你必须有
You could try this. It doesn't read all of f into memory at once (using the file object's iterator) and it closes the file when the code leaves the with block.
If you're using an older version of python (pre 2.6) you'll have to have
循环遍历文件。
Loop through the file.
你尝试了吗
?
只读取“一行”,另一方面
读取整行并为您提供所有行的列表。
Did you try
?
only reads "a line", on the other hand
reads whole lines and gives you a list of all lines.