程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Detailed explanation of the two methods of reading Python files read and readlines

編輯:Python

Catalog

introduction

.read([size]) Method

.readlines() Method

introduction

with open() as and open() It's all open , Not yet Read in file

hypothesis test.fa The content of is shown in the figure below :

ACGACGTAGCGTAGCTACGAT
CAGCGACGAGCTAGCGACGA

.read([size]) Method

read([size]) Method reads from the current location of the file size Bytes , If there is no parameter size, It means that the file is read until the end of the file , It returns a string object .

with open('test.fa') as fa: f = fa.read() print(f) print(type(f)) print('------') f = f.split('\n') print(f[0])

Return results

CGACGTAGCGTAGCTACGAT
CAGCGACGAGCTAGCGACGA
<class 'str'>
------
CGACGTAGCGTAGCTACGAT

.readlines() Method

readlines() Method to read all lines , Save in a list (list) variable , Each line as an element , Be similar to fa.read().split('\n') Result .

readlines Read all lines , And output in list form , You can use subscripts to locate each line

with open('test.fa') as fa: f = fa.readlines() print(type(f)) print(f[0]) print('------') print(f[1])##2. readlines() Method

Return results

<type 'list'>
CGACGTAGCGTAGCTACGAT
------
CAGCGACGAGCTAGCGACGA

That's all python File read read And readlines The two methods use detailed content , More about python File read read readlines Please pay attention to other relevant articles of software development network !



  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved