1

Im trying to create a program which only reads/prints a certain line in python. So far i have got this:

import random
import time
a = open("settings.txt", "r")
b = open("settings.txt", "a")
adding = input("Enter Name: ")
with open("settings.txt", "a") as f:
     f.write("\n{}".format(adding))
data = [line.rstrip() for line in a.readlines()]
print(", ".join(data))
time.sleep(10)

In my settings.txt:

Blah 1 
Blah 2
Blah 3

How do I only get the program to print (for example) Blah 1 and nothing else from that txt file?

PythonBeginner
  • 169
  • 4
  • 4
  • 12
  • 1
    How about using `a.readline()`? – lurker Dec 13 '13 at 22:56
  • Always just the first line, or a random line (is that why you import random)? – Barmar Dec 13 '13 at 22:57
  • the `data =` line puts all of the lines into a list... so just `print(data[0])` ? – TehTris Dec 13 '13 at 22:57
  • random will be used later on but just printing any line from that txt file. – PythonBeginner Dec 13 '13 at 22:58
  • 2
    You're using list comprehension and you don't know it's a list? Ouch.. – aIKid Dec 13 '13 at 23:01
  • As a side note, there is no reason to use `a.readlines()`. Just use `a`, and you'll get the same results—but without having to first copy everything into a big list an extra time. – abarnert Dec 13 '13 at 23:02
  • 1
    Also, if you don't need all the lines, why read all the lines in the first place? Just use [`linecache.getline`](http://docs.python.org/2/library/linecache.html). – abarnert Dec 13 '13 at 23:03
  • This program is eventually going to be a revision program for myself to help me study. some have like word-meaning so i would only want one line but i want it to read the whole thing so i can just refer to the line dead quick. if that makes sense – PythonBeginner Dec 13 '13 at 23:06

2 Answers2

3

The following opens up the file for you, prints the first line, and then closes it:

with open("settings.txt", "r") as f:
    print f.readline()
Eli
  • 36,793
  • 40
  • 144
  • 207
2

If it is just the first line, you could do:

for line in open('afile.txt'):
    print line
    break

If it is a random line that you want, you could do:

from random import choice
print choice(list(open('afile.txt')))
Ketan Maheshwari
  • 2,002
  • 3
  • 25
  • 31
  • Thank you very much! That will be helpful (random) in the later program!!:) – PythonBeginner Dec 13 '13 at 23:04
  • If afile.txt is large enough that you have to worry about fitting it into memory, you should not do `[f for f in open('afile.txt')]` (which is equivalent to `open('afile.txt').readlines()`). See http://stackoverflow.com/questions/448005/whats-an-easy-way-to-read-random-line-from-a-file-in-unix-command-line – IceArdor Dec 14 '13 at 01:15