Home  >  Article  >  Backend Development  >  How to read TXT files in Python

How to read TXT files in Python

不言
不言Original
2018-04-27 15:40:242339browse

The following is a summary of how to read TXT files in Python. It has a good reference value and I hope it will be helpful to everyone. Come and take a look together

Method 1:

<span style="font-size:14px;">#read txt method one 
f = open("./image/abc.txt") 
line = f.readline() 
while line: 
 print line 
 line = f.readline() 
f.close() 
 
</span>

Method Two:

#read txt method two 
f = open("./image/abc.txt") 
for line2 in open("./image/abc.txt"): 
 print line2

##Method Three:

#read txt method three 
f2 = open("./image/abc.txt","r") 
lines = f2.readlines() 
for line3 in lines: 
 print line3

1. If there are two columns in the TXT file, you can set an array and then obtain the data respectively

2. The above files use relative paths, of course. You can use absolute paths

Related recommendations:


How to read file names and generate lists using python

Read csv with python File and put the file into a list example explanation

The above is the detailed content of How to read TXT files in Python. 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