I have got a .txt file that contains a lot of lines. I would like my program to ask me what line I would like to print and then print it into the python shell. The .txt file is called packages.txt.
Asked
Active
Viewed 2.0k times
-1
-
2I tried: 'f=open('packages.txt') lines=f.readlines()' – EatMyApples May 06 '12 at 03:48
-
1sorry, i dont know how to format code...? – EatMyApples May 06 '12 at 03:50
-
2Code is best put into the *question*, rather than in comments. Indent your code four spaces using the `{}` toolbar button to format the code in the question. – Greg Hewgill May 06 '12 at 03:50
-
3No worries, you're new here. We don't expect you to know everything about the site right away. – Greg Hewgill May 06 '12 at 03:55
-
1So what didn't work? You described code to read the file; what do you suppose is the next logical step? – Karl Knechtel May 06 '12 at 04:28
-
for some reason it still printed the whole file, and all the lines – EatMyApples May 06 '12 at 04:47
-
Thanks for giving me -4 reputation guys. I am new to all this and dont really know how to use it. cheers – EatMyApples May 06 '12 at 05:12
-
possible duplicate of [Skip first couple of lines while reading lines in Python file](http://stackoverflow.com/questions/9578580/skip-first-couple-of-lines-while-reading-lines-in-python-file) – dawg May 06 '12 at 05:46
3 Answers
8
If you don't want to read in the entire file upfront, you could simply iterate until you find the line number:
with open('packages.txt') as f:
for i, line in enumerate(f, 1):
if i == num:
break
print line
Or you could use itertools.islice()
to slice out the desired line (this is slightly hacky)
with open('packages.txt') as f:
for line in itertools.islice(f, num+1, num+2):
print line

spinlok
- 3,561
- 18
- 27
4
If the file is big, using readlines is probably not a great idea, it might be better to read them one by one until you get there.
line_number = int(raw_input('Enter the line number: '))
with open('packages.txt') as f:
i = 1
for line in f:
if i == line_number:
break
i += 1
# line now holds the line
# (or is empty if the file is smaller than that number)
print line
(Updated to fix the mistake in the code)

Marga Manterola
- 642
- 1
- 4
- 12
-
Thank you, that worked. But for some reason if i enter 3 for example it will print from line 1-3? – EatMyApples May 06 '12 at 04:44
-
-
@VincenTTTTTTTTTTTT marga initialized `i` using `i==1`,which is wrong. it should be `i=1` – Ashwini Chaudhary May 06 '12 at 05:47
0
How to refer to a specific line of a file using line number ? as in java if line number = i and file is stored in f then f(i) would do.

Roy
- 33
- 6