Python 中 read()、readline() 和 readlines() 的区别 [英] Difference in read(), readline() and readlines() in Python

查看:55
本文介绍了Python 中 read()、readline() 和 readlines() 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看 网络 Python 标题中提到的命令及其区别;但是,我对这些命令的完整基本了解并不满意.

I was looking on a web of Python the commands mentioned in title and their difference; however, I have not satisfied with a complete basic understanding of these commands.

假设我的文件只有以下内容.

Suppose my file has only the following content.

这是我第一次在这个网站上提出问题,如果有人能澄清我对学习 Python 的疑问,我将不胜感激.我感谢 StackOverflow 提供这个平台.

在命令read()readline()readlines()中,一个区别当然是读取整个文件,或者单行,或指定行.

In the commands read(), readline() and readlines(), one difference is of course reading whole file, or a single line, or specified line.

但我不明白这些命令中括号 () 的使用/必要性.例如,readline()readline(7) 有什么区别?如果参数 7 超过文件中的行数,会输出什么?

But I didn't understand the use/necessity of bracket () in these commands. For example, what is the difference in readline() and readline(7)? If the argument 7 exceeds the number of lines in the file, what will be output?

在上面提到的网页上,解释了read() 中的参数是做什么的;但是没有提到 readline()readlines() 中的参数是做什么的?

On the web mentioned above, it is explained what the argument in read() does; but it is not mentioned what the argument in readline() or readlines() does?

推荐答案

read(n)
filevar.read()

读取并返回 n 个字符的字符串,如果未提供 n,则将整个文件作为单个字符串返回.

Reads and returns a string of n characters, or the entire file as a single string if n is not provided.

readline(n)
filevar.readline()

返回文件的下一行,其中包含包括换行符在内的所有文本.如果将 n 作为参数提供,则如果行长于 n,则仅返回 n 个字符.

Returns the next line of the file with all text up to and including the newline character. If n is provided as a parameter than only n characters will be returned if the line is longer than n.

readlines(n)
filevar.readlines()

返回一个字符串列表,每个字符串代表文件的一行.如果未提供 n,则返回文件的所有行.如果提供了 n,则读取 n 个字符,但将 n 舍入以返回整行.

Returns a list of strings, each representing a single line of the file. If n is not provided then all lines of the file are returned. If n is provided then n characters are read but n is rounded up so that an entire line is returned.

这篇关于Python 中 read()、readline() 和 readlines() 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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