python中read、readline
read 读取整个文件
readline 读取下一行
readlines 读取整个文件到一个迭代器以供我们遍历
例:read方法打印文件里所有字符串
- for line in open('artifacts.xml').read():
- print(line)
-
- <
- ?
- x
- m
- l
- …………
- f.read()
- Out[1]: "<?xml version='1.0' encoding='UTF-8'?>\n<?artifactRepository version='1.1.0'?>\n
readline方法只打印下一行的所有字符串
- for line in open('artifacts.xml').readline():
- print(line)
-
- <
- ?
- x
- m
- l
- ……
- f = open('artifacts.xml')
- f.readline()
- Out[1]: "<?xml version='1.0' encoding='UTF-8'?>\n"
- f.readline()
- Out[1]: "<?artifactRepository version='1.1.0'?>\n"
readlines则是打印出所有行
- for line in open('artifacts.xml').readlines():
- print(line.strip())
-
- <?xml version='1.0' encoding='UTF-8'?>
- <?artifactRepository version='1.1.0'?>
-
- f = open('artifacts.xml')
- f.readlines()
- Out[1]:
- ["<?xml version='1.0' encoding='UTF-8'?>\n",
- "<?artifactRepository version='1.1.0'?>\n"]
可以看出直接使用 readlines方法 返回的是一个列表,readline返回的是字符串。
相关文章