Python File readlines() usage

不言
Release: 2018-04-23 15:31:16
Original
2110 people have browsed it

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()
Copy after login

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()
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!