Home  >  Article  >  Backend Development  >  Python File readlines() usage

Python File readlines() usage

不言
不言Original
2018-04-23 15:31:162170browse

readlines() method is used to read all lines (until the end character EOF) and return a list. The list can be processed by Python's for... in ... structure. If the end character EOF is encountered, it returns empty. String, friends who need it can refer to

Overview

##readlines() method is used to read all lines (until the end character EOF) And returns a list, which can be processed by Python's for... in ... structure.

If the end character EOF is encountered, an empty string is returned.

Syntax

##readlines()

The method syntax is as follows: fileObject.readlines( );

Parameter

None.


Return value

Returns a list containing all rows.


Example

The following example demonstrates the use of the readline() method:
The content of the file jb51.txt is as follows:

1:www.jb51.net
2:www.jb51.net

3:www.jb51.net
4:www.jb51.net
5:www.jb51.net

Loop to read the contents of the file:

How to write python2

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 打开文件
fo = open("jb51.txt", "r")
print "文件名为: ", fo.name
 
for line in fo.readlines():             #依次读取每行 
  line = line.strip()               #去掉每行头尾空白 
  print "读取的数据为: %s" % (line)
 
# 关闭文件
fo.close()

How to write python3

# -*- coding: utf-8 -*-
# 打开文件
fo = open("jb51.txt", "r")
print("文件名为: ",fo.name)
 
for line in fo.readlines():             #依次读取每行 
  line = line.strip()               #去掉每行头尾空白 
  print ("读取的数据为: %s" % (line))
 
# 关闭文件
fo.close()

The effect is as shown below



##

The above is the detailed content of Python File readlines() usage. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn