I have created a text file in python and I am struggling to find out how to print certain lines from the text file in python. hope someone can help me. I know it has something to do with f.write or f.read.
Asked
Active
Viewed 850 times
-5
-
2Possible duplicate of [Python: read file line by line into array](http://stackoverflow.com/questions/3277503/python-read-file-line-by-line-into-array) – Feb 19 '16 at 13:19
-
1You might have missed the part about [Reading and Writing Files](https://docs.python.org/3.5/tutorial/inputoutput.html#reading-and-writing-files) in the tutorial. – Matthias Feb 19 '16 at 13:30
3 Answers
0
You could try something like this:
f = open("C:/file.txt", "r") #name of file open in read mode
lines = f.readlines() #split file into lines
print(lines[1]) #print line 2 from file

Mark Skelton
- 3,663
- 4
- 27
- 47
0
with open('data.txt') as file_data:
text = file_data.read()
if you are using *.json files good solution is:
data = json.loads(open('data.json').read()))

Bohdan Biloshytskiy
- 375
- 1
- 12
0
Use the with
keyword to automatically handle file closing after opening the file.
with open("file.txt", "r") as f:
for line in f.readlines():
print line #you can do whatever you want with the line here
This handles file closing even if your program breaks during execution. The other - manual way of doing the same is:
f = open("file.txt", "r")
for line in f:
print line
f.close()
But beware that closing here happens only after your loop is executed. See also this answer Link

Community
- 1
- 1

meltdown90
- 251
- 1
- 11